diff --git a/docs/clarity/index.md b/docs/clarity/index.md index 903de93a45..a90f91b599 100644 --- a/docs/clarity/index.md +++ b/docs/clarity/index.md @@ -23,11 +23,11 @@ One of the core precepts of Clarity is that it is secure by design. The design p ### Clarity is interpreted, not compiled -Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts?2 With Clarity, what you see is what you get. +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. ### Clarity is decidable -A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. If you are unsure what this means, let it not worry you for now. The serious advantage of decidability will become more apparent over time. +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). ### Clarity does not permit reentrancy diff --git a/docs/clarity/language-functions.md b/docs/clarity/language-functions.md new file mode 100644 index 0000000000..6848e5ed1f --- /dev/null +++ b/docs/clarity/language-functions.md @@ -0,0 +1,2246 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `true`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that +_unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to +is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions +which must return the same type. In the case that the boolean input is `true`, the +`if` function evaluates and returns `expr1`. If the boolean input is `false`, the +`if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, +evaluating each expression and _binding_ it to the corresponding variable name. +`let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. +The _context_ created by this set of bindings is used for evaluating its body expressions. +The let expression returns the value of the last such body expression. +Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +The `map` function applies the function `func` to each corresponding element of the input sequences, +and outputs a _list_ of the same type containing the outputs from those function applications. +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, +for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. +The `func` argument must be a literal function name. +Also, note that, no matter what kind of sequences the inputs are, the output is always a list. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type +`B` by recursively applies the function `func` to each element of the +input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the +first element of `sequence_A`. The resulting value of type `B` is used for the +next application of `func`, along with the next element of `sequence_A` and so +on. `fold` returns the last value of type `B` returned by these successive +applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, +for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. +The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, +and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `concat` function takes two sequences of the same type, +and returns a concatenated sequence of the same type, with the resulting +sequence_len = sequence1_len + sequence2_len. +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. +The function returns an optional type. If the input sequence length is less than +or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. +` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. +` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, +for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. +` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be +found, using `is-eq` checks, in the provided sequence. +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, +for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. +If the target item is not found in the sequence (or if an empty string or buffer is +supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each +supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. +The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the +inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. +The value is looked up using `key-tuple`. +If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, +it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the +inputted value. This function performs a _blind_ update; whether or not a value is already associated +with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, +and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the +inputted value if and only if there is not already a value associated with the key in the map. +If an insert occurs, the function returns `true`. If a value already existed for +this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, +and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for +the given map. If an item exists and is removed, the function returns `true`. +If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. +A `get` function can use typed tuples as input to select specific values from a given tuple. +Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and +associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. +If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in +the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the +return value of the last such expression. +Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. +If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the +integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. +If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the +integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. +If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the +integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated +to 256 bits) of the inputted value. +If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the +integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. +Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) +is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` +with the provided `signature`. +If the signature does not match, it will return the error code `(err u1).`. +If the signature is invalid, it will return the error code `(err u2).`. +The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash +was signed with the private key that generated the public key. +The `message-hash` is the `sha256` of the message. +The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core +nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. +You _may not_ use this function to call a public function defined in the current contract. If the public +function returns _err_, any database changes resulting from calling `contract-call?` are aborted. +If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ +principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. +If the `public-key` is invalid, it will return the error code `(err u1).`. +` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the +block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +Note: The block identifying hash must be a hash returned by the `id-header-hash` block information +property. This hash uniquely identifies Stacks blocks and is unique across Stacks forks. While the hash returned by +`header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The +value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does +not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names +are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +The `time` property returns an integer value of the block header time field. This is a Unix epoch timestamp in seconds +which roughly corresponds to when the block was mined. **Warning**: this does not increase monotonically with each block +and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for +creating return values in public functions. An _err_ value indicates that any database changes during +the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for +creating return values in public functions. An _ok_ value indicates that any database changes during +the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is +a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, +`default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: +if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. +If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current +control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is +an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the +option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns +the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, +`unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (map-get? names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument +is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. +If the supplied argument is an `(ok ...)` value, +`unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is +an option type, and the argument is a `(some ...)` option, this function returns the inner value of the +option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns +the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, +`unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument +is an `(err ...)` response, `unwrap` returns the inner value of the `err`. +If the supplied argument is an `(ok ...)` value, +`unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided +`input` is a `some` or `none` option, and evaluates `some-branch` or +`none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` +argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is +an `ok` or `err` response type, and evaluates `ok-branch` or +`err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` +argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` +argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the +response object be determinable. For situations in which one of the parts of a response +is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is +an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the +option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns +the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, +`try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, +and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, +and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, +and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, +and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the +input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, +for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. +The `func` argument must be a literal function name. +` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. +The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. +The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in +that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token +type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, +any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns +one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer +`(err u2)` -- `sender` and `recipient` are the same principal +`(err u3)` -- amount to send is non-positive +` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` +from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` +must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. +When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns +one of the following error codes: + +`(err u1)` -- `sender` does not own the asset +`(err u2)` -- `sender` and `recipient` are the same principal +`(err u3)` -- asset identified by asset-identifier does not exist +` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. +The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in +that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. +` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token +type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but +rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it +returns `(ok true)`. +` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. +The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token +type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but +rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it +returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. +The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in +that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. +` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` +principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal +by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns +one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer +`(err u2)` -- `sender` and `recipient` are the same principal +`(err u3)` -- amount to send is non-positive +`(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying +the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns +one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer +`(err u3)` -- amount to send is non-positive +`(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. +The expression passed into the definition is evaluated at contract launch, in the order that it is +supplied in the contract. This can lead to undefined function or undefined variable errors in the +event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private +functions may not be called from other smart contracts, nor may they be invoked directly by users. +Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract +definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public +functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction +to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract +definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by +a public function is aborted if the function returns an `err` type. Public functions may be invoked by other +contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such +functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract +definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions +may not perform any datamap modifications, or call any functions which +perform such modifications. This is enforced both during type checks and during +the execution of the function. Public read-only functions may +be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such +maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract +definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such +variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract +definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` +function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply +of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract +definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. +Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset +identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract +definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts +can implement a given trait and then have their contract identifier being passed as function arguments in order to be called +dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract +definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent +references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be +using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract +definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. +Additional checks are being performed when the contract is being published, rejecting the deployment if the +contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified +('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract +definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (get-balance (account principal)) + (ok u0)) +(define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/docs/clarity/language-keywords.md b/docs/clarity/language-keywords.md new file mode 100644 index 0000000000..9cde839e05 --- /dev/null +++ b/docs/clarity/language-keywords.md @@ -0,0 +1,147 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that +contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/docs/clarity/noteworthy-contracts/_category_.json b/docs/clarity/noteworthy-contracts/_category_.json index 14b9388b4d..eb32d48e32 100644 --- a/docs/clarity/noteworthy-contracts/_category_.json +++ b/docs/clarity/noteworthy-contracts/_category_.json @@ -1,6 +1,6 @@ { "label": "Noteworthy Contracts", - "position": 4, + "position": 5, "link": { "type": "generated-index", "description": "Specific deployed Clarity Contracts worth mentioning." diff --git a/docs/clarity/noteworthy-contracts/stacking-contract.md b/docs/clarity/noteworthy-contracts/stacking-contract.md index c0027256cd..6a204159d3 100644 --- a/docs/clarity/noteworthy-contracts/stacking-contract.md +++ b/docs/clarity/noteworthy-contracts/stacking-contract.md @@ -145,7 +145,7 @@ This is the self-service interface. tx-sender will be the Stacker. - The given stacker cannot currently be stacking. - You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. -- The pox-addr argument must represent a valid reward address. Right now, this must be a Bitcoin p2pkh or p2sh address. It cannot be a native Segwit address, but it may be a p2wpkh-p2sh or p2wsh-p2sh address. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). The tokens will unlock and be returned to the Stacker (tx-sender) automatically. diff --git a/docs/clarity/security/decidable.md b/docs/clarity/security/decidable.md new file mode 100644 index 0000000000..7d5411e382 --- /dev/null +++ b/docs/clarity/security/decidable.md @@ -0,0 +1,179 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. +A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. +Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using +non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, +Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. +Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/docs/clarity/security/index.md b/docs/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/docs/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/docs/cookbook/creating-an-nft.md b/docs/cookbook/creating-an-nft.md index 08faf9393a..851189579e 100644 --- a/docs/cookbook/creating-an-nft.md +++ b/docs/cookbook/creating-an-nft.md @@ -8,7 +8,7 @@ Clarity makes creating NFTs incredibly easy. With built-in functions for creatin Let's see how. :::tip -Code for this recipe has been pulled from [this NFT tutorial](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) from Developer DAO. +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). ::: ## Trait diff --git a/docs/cookbook/get-sats-per-stx.md b/docs/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/docs/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/docs/cookbook/index.md b/docs/cookbook/index.md index a2b0e42eea..9a40e62b46 100644 --- a/docs/cookbook/index.md +++ b/docs/cookbook/index.md @@ -13,11 +13,15 @@ Got an idea you think would make a good addition? We're always [accepting contri ## Bitcoin Integration -Swapping between Bitcoin and Stacks addresses +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) -Swapping between xBTC and BTC +Getting a Stacks address from a public key -Verifying a transaction on the BTC chain +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) ## DAOs @@ -33,8 +37,6 @@ Creating a BTC-backed DAO treasury Minting an NFT with Bitcoin -Airdropping an NFT to a Bitcoin address - ## Stacking and Mining Simple stacking pool @@ -45,10 +47,6 @@ Simple mining pool Proof of PoX payout -## Oracles - -Creating a simple BTC price oracle - ## Frontend [Post conditions with Stacks.js](./post-conditions) @@ -57,6 +55,8 @@ Creating a simple BTC price oracle [Sending transactions with Stacks.js](./stacks-js-sending-transactions) +Authenticating with Sign in with Stacks + ## Complete Apps [Sup](https://github.com/kenrogers/sup) diff --git a/docs/cookbook/parse-a-btc-tx.md b/docs/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/docs/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/docs/cookbook/sending-bitcoin-with-hiro-wallet.md b/docs/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/docs/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/docs/cookbook/verifying-a-btc-tx-was-mined.md b/docs/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/docs/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/docs/intro.md b/docs/intro.md index 951a0e5824..f284f060c8 100644 --- a/docs/intro.md +++ b/docs/intro.md @@ -15,6 +15,18 @@ These docs serve as: If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + ## Tutorials Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. diff --git a/docs/nakamoto/bitcoin-mev-mitigation.md b/docs/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/docs/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/docs/nakamoto/block-production.md b/docs/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/docs/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/docs/nakamoto/clarity-wasm.md b/docs/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/docs/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/docs/nakamoto/index.md b/docs/nakamoto/index.md new file mode 100644 index 0000000000..979febfe7c --- /dev/null +++ b/docs/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc&sort=title&state=open). diff --git a/docs/nakamoto/neon.md b/docs/nakamoto/neon.md new file mode 100644 index 0000000000..ece2bc3372 --- /dev/null +++ b/docs/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/docs/nakamoto/signer.md b/docs/nakamoto/signer.md new file mode 100644 index 0000000000..8f5f3d9921 --- /dev/null +++ b/docs/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property `stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/docs/nakamoto/stacking.md b/docs/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/docs/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/docs/stacks-academy/authentication.md b/docs/stacks-academy/authentication.md index 6768e8ba8b..55b89ee93b 100644 --- a/docs/stacks-academy/authentication.md +++ b/docs/stacks-academy/authentication.md @@ -18,7 +18,7 @@ The authentication flow with Stacks is similar to the typical client-server flow An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. -These tokens are are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: diff --git a/docs/stacks-academy/bns.md b/docs/stacks-academy/bns.md index c1257855a9..66b21d2640 100644 --- a/docs/stacks-academy/bns.md +++ b/docs/stacks-academy/bns.md @@ -65,8 +65,7 @@ guarantees _two_ of these properties. This limits how useful they can be. have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. -- In PGP, names are key IDs. They are - are globally unique and cryptographically owned, but not human-readable. PGP +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. @@ -330,7 +329,7 @@ subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. -# BNS and DID Standards +## BNS and DID Standards BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol diff --git a/docs/stacks-academy/btc-connection.md b/docs/stacks-academy/btc-connection.md index 5f7e7f32bb..1fd8b988c3 100644 --- a/docs/stacks-academy/btc-connection.md +++ b/docs/stacks-academy/btc-connection.md @@ -14,13 +14,37 @@ This topic is a bit of a rabbit hole, and this section of Stacks Academy is pret Let's get into it. -## Stacks Among Other Bitcoin Layers +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: -In the [last section](./what-is-stacks.md) we covered what Stacks actually is and what problem it is solving, but this is not a new problem. The Bitcoin write problem has been a bit of a holy grail problem in the crypto world for a while now. +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. -Bitcoin is the OG cryptocurrency and has the largest market cap, but it also some of the least functionality, which means if we want to make it a productive asset and use it to build a decentralized economy, we need to take a layered approach and let Bitcoin do what it does best, while creating additional layers on top of it to add functionality. +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. -So how does Stacks compare to some of the other approaches to layering on top of Bitcoin? +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. ### Lightning @@ -56,6 +80,32 @@ The Liquid consensus mechanism is managed by 15 functionaries, who handle the tr This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + ## Why Does Stacks Need a Token? This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. @@ -70,27 +120,18 @@ This is why networks like Lightning and other P2P networks don't need tokens, th Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. -But because it has its own execution environment and smart contract state to maintain, it needs a token to incentivize maintenance of the network. - -But it goes further than that. It is possible to build a system like this without a token using something like merge-mining or a sidechain, but then we lose out on the additional benefit of having the chain state's safety underpinned by its entire token economy's value. - -In the case of Stacks, the safety and liveness of the chain are underpinned by this value, and the stacking mechanism incentivizes network members to increase this value. - -From Jude Nelson, Stacks core developer: - -"How hard is it to cause a safety failure (i.e. a double-spend via a reorg) on just the canonical Stacks chain fork? Anyone can become a miner by spending BTC, so without loss of generality, reverting the last block on the canonical chain is at least as hard in expectation as spending more BTC than the rest of the miners combined for that block. Because each Bitcoin block selects at most one Stacks block, the act of reorging the canonical Stacks chain back N blocks is the act of winning at least N + 1 blocks built off of a common ancestor that is N blocks deep. This is a lower bound on the number of Bitcoin blocks mined during which a reorg needs to take place — in practice, honest miners will keep working on the canonical chain, and will win some Stacks blocks of their own, which in turn increases the number of Stacks blocks the reorging miners must win. - -How costly is it to carry out a reorg of N blocks? It’s a function of how valuable STX is relative to BTC — the more valuable STX are, the more BTC honest miners are committing to mining (this has borne out in practice), and thus the more BTC a reorging miner must commit. Therefore, the cost of a reorg is a function of the value of STX. +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. -This is similar to the economic security of a PoW blockchain. Like in PoW, each fork of the Stacks chain has its own independent “security budget” — an attacker must out-spend the security budget to carry out a reorg, and the security budget is a function of the block rewards. In PoX, the only difference is that the miners spend another blockchain’s tokens (BTC in Stacks’ case) instead of energy. Therefore, Stacks can’t be a sidechain, a drivechain, or a merge-mined chain, because none of these other systems’ security budgets are a function of their tokens’ worth. Sidechains, drivechains, and merged-mined chains all rely on external miners for their safety, since their safety is guaranteed in part by external miners validating their blocks. The onus on these systems is to get external miners to care enough to do so, and in the case of sidechains, drivechains, and blind merged-mined chains, there is an additional onus to encourage their nodes to mine blocks at all (since there is no on-chain reward for them to earn by doing so). By contrast, disinterested Bitcoin miners neither assist nor prevent a reorg in PoX — they only record the history of all Stacks forks. +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): -PoX offers two additional, unique security properties on top of PoW. First, no matter how much BTC a reorging miner can commit, the act of executing a reorg is going to be time-consuming. Unless the attacker can attack the Bitcoin chain itself by quickly producing a better Bitcoin fork, a reorging miner must sustain the attack for at least N + 1 Bitcoin blocks. This gives honest miners and users ample time to notice and react to the reorg attempt. +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers -Second, the history of block production in all Stacks forks is embedded within Bitcoin. This allows the system to leverage Bitcoin’s security budget in order to ensure that all forks are public. This is because the act of producing a hidden Stacks fork, where the fork’s block hashes are not known to the honest miners, is the act of producing a hidden canonical Bitcoin fork. Therefore, the act of producing a hidden Stacks fork is at least as hard as reorging the Bitcoin chain. A PoX chain leverages this property not to prevent reorgs, but to make reorgs unprofitable. +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. -By anchoring blocks to an existing blockchain, a PoX chain forces reorgs to happen out in the open, thereby giving advance warning to all honest network participants when they happen. Honest miners, users, and exchanges will see the PoX transactions for reorg attempts on the existing blockchain, and adapt their behaviors accordingly: honest miners will increase their commitments, and users and exchanges will require more confirmations for transactions. This makes the act of carrying out a reorg while also making a profit much more challenging, since malicious reorgs — like selfish mining and double-spending — rely on secrecy to work effectively. Specific to Stacks, miners are additionally required to mine for a “warm-up” period of two blocks, during which they must spend BTC at their target commit levels but will not win any Stacks blocks. So, a high-budget reorg attempt will not only be costly, but will also alert the rest of the network before the damage is done." +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. -- [What Kind of Blockchain is Stacks?](https://stacks.org/stacks-blockchain) +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. ## The Symbiotic Relationship Between Stacks and Bitcoin diff --git a/docs/stacks-academy/sips.md b/docs/stacks-academy/sips.md index 1397b6a65f..c70cc5866b 100644 --- a/docs/stacks-academy/sips.md +++ b/docs/stacks-academy/sips.md @@ -17,7 +17,7 @@ The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) Anyone in the Stacks community can submit a SIP. :::tip Stacks Improvement Proposals Community Calls -Add the [weekly community SIP call](https://www.addevent.com/event/IJ15791776) to your calendar. +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) @@ -37,7 +37,10 @@ More details of the meetings are available [here](https://github.com/stacksgov/s - [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) - [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) - [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) - [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) ## How to Get Involved diff --git a/docs/stacks-academy/stacking.md b/docs/stacks-academy/stacking.md index 60531dfced..846152ecf9 100644 --- a/docs/stacks-academy/stacking.md +++ b/docs/stacks-academy/stacking.md @@ -6,11 +6,45 @@ sidebar_position: 11 ## Introduction -Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. It is crucial to note that this has no impact on block production or validation. Stacks is not a Proof-of-Stake network and stacking is different than staking. +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. ![](/img/stacking.png) -Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks 2.0 network. +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. :::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). @@ -55,7 +89,7 @@ Stacks (STX) token holders don't automatically receive stacking rewards. Instead - Commit to participation before a reward cycle begins - Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum - Lock up STX tokens for a specified period -- Provide a supported Bitcoin address to receive rewards (native segwit is not supported) +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. @@ -80,13 +114,9 @@ Stacking is a built-in capability of PoX and occurs through a set of actions on ## Bitcoin address -:::danger -You must provide a BTC address in one of two formats: - -- [Legacy (P2PKH)](https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash), which starts with `1`. - -- [Segregated Witness / Segwit (P2SH)](https://en.bitcoin.it/wiki/Pay_to_script_hash), which starts with `3`. The "Native Segwit" format (which starts with `bc1`), for example, is not supported. - ::: +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. diff --git a/docs/stacks-academy/technical-specs.md b/docs/stacks-academy/technical-specs.md index 695f849e1a..6f9fe1599e 100644 --- a/docs/stacks-academy/technical-specs.md +++ b/docs/stacks-academy/technical-specs.md @@ -40,7 +40,7 @@ sidebar_position: 13 - Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. - Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). - Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). -- Only two types of BTC reward addresses are supported: [Legacy (P2PKH)](https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash) or [Segregated Witness / Segwit (P2SH)](https://en.bitcoin.it/wiki/Pay_to_script_hash). Native Segwit is not supported. +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot - Further reading: [Stacking](stacking) ## Accounts and Addresses diff --git a/docs/stacks-academy/testnet.md b/docs/stacks-academy/testnet.md index f8b9f03df2..da2e561fd1 100644 --- a/docs/stacks-academy/testnet.md +++ b/docs/stacks-academy/testnet.md @@ -10,9 +10,13 @@ The testnet is a separate blockchain from the Stacks mainnet analogous to a stag It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. -### Faucet +### Faucets -The testnet faucet provides you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. You can get STX from the faucet on the [Stacks Explorer Sandbox](https://explorer.stacks.co/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. @@ -24,6 +28,12 @@ You can also try out [Stacking](./stacking) by clicking on `I want to stack`. The Explorer Sandbox requires you to login with a Stacks wallet ::: +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + ### Testnet API The hosted Stacks Blockchain API for the testnet is available at this base URL: diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..c83c864810 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2031 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Importantly, the supplied arguments are evaluated in-order and lazily. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` A + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +Also, note that, no matter what kind of sequences the inputs are, the output is always a list. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `func` argument must be a literal function name. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` A + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +This hash uniquely identifies Stacks blocks and is unique across Stacks forks. Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. The `time` property returns an integer value of the block header time field. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/de/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/de/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..b2fef628f9 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/de/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/de/docusaurus-plugin-content-docs/current/contribute/translations.md index bd9a452333..fe8f8c6027 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/de/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2067e7d57c..3f58ca5e68 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/de/docusaurus-plugin-content-docs/current/gaia/gaia.md index 1070857350..f86a0d61dc 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/de/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/de/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/de/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/intro.md b/i18n/de/docusaurus-plugin-content-docs/current/intro.md index 84f1eaa649..f284f060c8 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Docs Introduction +# Stacks Docs -Welcome to the community driven official Stacks Documentation. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Learn about Stacks mining, the STX token, and the Clarity smart contract language. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/de/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/de/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..15df918d04 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 59528c33e1..5afd34c23f 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,195 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` - -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` +### Update the Bitcoin Configuration File - +Next, update the bitcoin configuration: -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... - -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). +--- -### Enable debug logging +## Running a Stacks Blockchain miner -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -## Running a miner in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Prerequisites +### Generate a keychain -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -### Generate keychain and get mainnet tokens in Windows - -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -203,167 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +### Update the Stacks Blockchain Configuration File -Update the following properties: +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -```toml -[node] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Next, update the bitcoin configuration: -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) -[burnchain] -... +```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... - -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -374,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -389,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -400,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index 3e2343d344..c0a27e63d5 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,153 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. +### Start Bitcoin -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... - -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -197,161 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -Request BTC from faucet: +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` -### Update configuration file +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update the Stacks Blockchain Configuration File -Update the following properties: +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -```toml -[node] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Next, update the bitcoin configuration: -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) -[burnchain] -... +```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). - -### Update config file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... - -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -362,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -375,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -405,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 89af343dc6..cd216e7103 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/de/docusaurus-plugin-content-docs/current/references/glossary.md index ebb24ca97b..5453fc9a41 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). More information and example [here](../services-using-stacks/wallets). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..55d0165def --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..9e854e54f2 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Register and sign in users with identities on the Stacks blockchain +sidebar_position: 8 +--- + +## Introduction + +This guide explains how authentication is performed on the Stacks blockchain. + +Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## How it works + +The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. The app private key serves three functions: + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..9f88fabff4 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,242 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." +``` + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Subdomain Creation and Management + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Each name in BNS has an associated DID. The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..9310aa65be --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..e6e93e130a --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..dd50cb7ee1 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,151 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +}' +}' +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a6f9b9ac96 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..ad9bb1822e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introduction +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..ba6b18f0f7 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/de/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 59934a5bde..ba6dee45a9 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/de/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index 45be763e21..c650b3ef10 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `func` argument must be a literal function name. Applicable sequence types a ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1385,4 +1390,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the ```clarity (impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/blockchain/index.md b/i18n/es/docusaurus-plugin-content-docs/current/blockchain/index.md index 13db24ec30..c9ecad8bd4 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/blockchain/index.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/blockchain/index.md @@ -1,28 +1,28 @@ --- title: Blockchain -description: Stacks Blockchain +description: Blockchain de Stacks sidebar_position: 6 --- -Below is a guide to start working locally with the Stacks Blockchain. +A continuación hay una guía para empezar a trabajar localmente con la Blockchain de Stacks. -Code repository is [here](https://github.com/stacks-network/stacks-blockchain). +El código está alojado en este [repositorio de Github](https://github.com/stacks-network/stacks-blockchain). -## Getting started with the Stacks Blockchain +## Empezando con la Blockchain de Stacks -### Download and build stacks-blockchain +### Descargar y compilar la blockchain de Stacks -The first step is to ensure that you have Rust and the support software installed. +El primer paso es asegurarse de que tiene Rust y el software de soporte instalado. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` :::info -For building on Windows, follow the rustup installer instructions at https://rustup.rs/ +Para compilar en Windows, sigue las instrucciones del instalador de rustup en https://rustup.rs/ ::: -From there, you can clone the Stacks Blockchain repository: +Desde allí, puede clonar el repositorio de la Blockchain de Stacks: ```bash git clone --depth=1 https://github.com/stacks-network/stacks-blockchain.git @@ -30,21 +30,21 @@ git clone --depth=1 https://github.com/stacks-network/stacks-blockchain.git cd stacks-blockchain ``` -Then build the project: +Luego compile el proyecto: ```bash cargo build ``` -Run the tests: +Ejecuta las pruebas: ```bash cargo test testnet -- --test-threads=1 ``` -### Encode and sign transactions +### Codificar y firmar transacciones -Here, we have generated a keypair that will be used for signing the upcoming transactions: +Aquí, hemos generado un par de claves que se utilizará para firmar las próximas transacciones: ```bash cargo run --bin blockstack-cli generate-sk --testnet @@ -57,7 +57,7 @@ cargo run --bin blockstack-cli generate-sk --testnet # } ``` -This keypair is already registered in the `testnet-follower-conf.toml` file, so it can be used as presented here. +Este par de claves ya está registrado en el archivo `testnet-follower-conf.toml`, por lo que puede ser usado como se presenta aquí. We will interact with the following simple contract `kv-store`. In our examples, we will assume this contract is saved to `./kv-store.clar`: diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..859fb5a1fa --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Resumen y guías para comenzar con Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..ff13c975c9 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2030 @@ +--- +title: Funciones +description: Vea una lista detallada de todas las funciones del lenguaje Clarity. +sidebar_position: 3 +tags: + - clarity +--- + +## Funciones + +Lista detallada de todas las funciones de Clarity. + +### + (add) + +#### entrada: `A` + +#### salida: `int | uint` + +#### firma: `(+ i1 i2...)` + +#### descripción: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### ejemplo: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### entrada: `int, ... | uint, ...` + +#### salida: `int | uint` + +#### firma: `(- i1 i2...)` + +#### descripción: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### ejemplo: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### entrada: `int, ... | uint, ...` + +#### salida: `int | uint` + +#### firma: `(* i1 i2...)` + +#### descripción: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### ejemplo: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### entrada: `A` + +#### salida: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### descripción: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### ejemplo: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### entrada: `int, int | uint, uint` + +#### salida: `bool` + +#### firma: `(>= i1 i2)` + +#### descripción: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### ejemplo: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### entrada: `int, int | uint, uint` + +#### salida: `bool` + +#### signature: `(<= i1 i2)` + +#### descripción: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### ejemplo: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### entrada: `int, int | uint, uint` + +#### salida: `bool` + +#### signature: `(< i1 i2)` + +#### descripción: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### ejemplo: + +```clarity +(< 1 2) ;; Devuelve true +(< 5 2) ;; Devuelve false +``` + +### > (greater than) + +#### entrada: `int, int | uint, uint` + +#### salida: `bool` + +#### signature: `(> i1 i2)` + +#### descripción: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### ejemplo: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### entrada: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### descripción: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### ejemplo: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### descripción: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### ejemplo: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### entrada: `int, int | uint, uint` + +#### salida: `int | uint` + +#### signature: `(mod i1 i2)` + +#### descripción: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### ejemplo: + +#### ejemplo: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### entrada: `int, int | uint, uint` + +#### salida: `int | uint` + +#### firma: `(pow i1 i2)` + +#### descripción: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### ejemplo: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### salida: `int | uint` + +#### firma: `(sqrti n)` + +#### descripción: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### ejemplo: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### salida: `int | uint` + +#### firma: `(log2 n)` + +#### descripción: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### ejemplo: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### entrada: `int, int | uint, uint` + +#### salida: `int | uint` + +#### firma: `(xor i1 i2)` + +#### descripción: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### ejemplo: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### entrada: `bool, ...` + +#### salida: `bool` + +#### firma: `(and b1 b2 ...)` + +#### descripción: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### ejemplo: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### entrada: `bool, ...` + +#### salida: `bool` + +#### signature: `(or b1 b2 ...)` + +#### descripción: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Importantly, the supplied arguments are evaluated in-order and lazily. + +#### ejemplo: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### salida: `bool` + +#### signature: `(not b1)` + +#### descripción: + +Devuelve la inversa de la entrada booleana. + +#### ejemplo: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### salida: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### descripción: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### ejemplo: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### descripción: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### ejemplo: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### entrada: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### salida: `A` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### descripción: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### ejemplo: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map-get? map-name key-tuple)` + +#### descripción: + +Also, note that, no matter what kind of sequences the inputs are, the output is always a list. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. + +#### ejemplo: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### descripción: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### ejemplo: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### descripción: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### ejemplo: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### descripción: + +The `func` argument must be a literal function name. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. + +#### ejemplo: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### descripción: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### ejemplo: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### descripción: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### ejemplo: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### descripción: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### ejemplo: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### descripción: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### ejemplo: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### descripción: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### ejemplo: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### descripción: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### ejemplo: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### salida: `bool` + +#### signature: `(var-set var-name expr1)` + +#### descripción: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### ejemplo: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### descripción: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### salida: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### descripción: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### salida: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### descripción: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### salida: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### descripción: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### descripción: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### ejemplo: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### descripción: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### descripción: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### ejemplo: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### entrada: `AnyType, ... A` + +#### output: `A` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### descripción: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### ejemplo: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### descripción: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### ejemplo: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### ejemplo: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### descripción: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### ejemplo: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### entrada: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### descripción: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### ejemplo: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### descripción: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### ejemplo: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### descripción: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### ejemplo: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### salida: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### descripción: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### ejemplo: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### descripción: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### ejemplo: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### firma: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### descripción: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### ejemplo: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### entrada: `A` + +#### salida: `A` + +#### firma: `(as-contract expr)` + +#### descripción: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### ejemplo: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### salida: `principal` + +#### signature: `(contract-of .contract-name)` + +#### descripción: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### ejemplo: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### ejemplo: + +```clarity +(principal-of? (principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### descripción: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +This hash uniquely identifies Stacks blocks and is unique across Stacks forks. Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### ejemplo: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? (define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? signature: (get-block-info? prop-name block-height-expr)` + +#### descripción: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. The `time` property returns an integer value of the block header time field. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### ejemplo: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### descripción: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### ejemplo: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### entrada: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### descripción: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### ejemplo: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### descripción: + +The `some` function constructs a `optional` type from the input value. + +#### ejemplo: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### descripción: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### salida: `bool` + +#### firma: `(asserts! bool-expr thrown-value)` + +#### descripción: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### ejemplo: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Devuelve true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### firma: `(unwrap! | uint, ...` + +#### descripción: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (map-get? names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### descripción: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### ejemplo: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### descripción: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### entrada: `(response A B)` + +#### salida: `B` + +#### firma: `(unwrap-err-panic response-input)` + +#### descripción: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### ejemplo: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### descripción: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### ejemplo: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### firma: `(try! A` + +#### descripción: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### entrada: `(response A B)` + +#### salida: `bool` + +#### signature: `(is-ok value)` + +#### descripción: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### ejemplo: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### salida: `bool` + +#### signature: `(is-none value)` + +#### descripción: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### ejemplo: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### entrada: `(response A B)` + +#### salida: `bool` + +#### signature: `(is-err value)` + +#### descripción: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### ejemplo: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### salida: `bool` + +#### signature: `(is-some value)` + +#### descripción: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### ejemplo: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### descripción: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### ejemplo: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### descripción: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### ejemplo: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? The asset must have been defined using define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### descripción: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### ejemplo: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### descripción: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### ejemplo: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### descripción: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### ejemplo: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### descripción: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### ejemplo: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### firma: `(ft-mint? token-name amount recipient)` + +#### descripción: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### ejemplo: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### descripción: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### ejemplo: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### descripción: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### ejemplo: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### descripción: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### ejemplo: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### descripción: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### ejemplo: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### descripción: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### ejemplo: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### descripción: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### ejemplo: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### descripción: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### ejemplo: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### descripción: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### ejemplo: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### descripción: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### ejemplo: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### descripción: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### ejemplo: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### descripción: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### ejemplo: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### descripción: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### ejemplo: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### descripción: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### ejemplo: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### descripción: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### ejemplo: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### descripción: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### ejemplo: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### descripción: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### ejemplo: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### descripción: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### ejemplo: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (get-balance (account principal)) + (ok u0)) +(define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..414f40a387 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Palabras clave +description: Vea una lista detallada de todas las palabras clave para el lenguaje Clarity. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Referencia de palabra clave + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### salida: `principal` + +#### descripción: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### ejemplo: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### salida: `principal` + +#### descripción: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### ejemplo: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### descripción: + +Returns the current block height of the Stacks blockchain as an uint + +#### ejemplo: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### descripción: + +Returns the current block height of the underlying burn blockchain as a uint + +#### ejemplo: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### descripción: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### ejemplo: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### salida: `bool` + +#### descripción: + +Boolean true constant. + +#### ejemplo: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### salida: `bool` + +#### descripción: + +Boolean false constant. + +#### ejemplo: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### descripción: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### ejemplo: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### salida: `bool` + +#### descripción: + +Returns whether or not the code is running in a regression test + +#### ejemplo: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..045d9a4289 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Tipos +description: Vea una lista detallada de todos los tipos para el lenguaje Clarity. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Tipos | Notas | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | Cadena ASCII de longitud máxima `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..ad9f9d75a7 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Contratos importantes", + "position": 5, + "link": { + "type": "generated-index", + "description": "Contratos de Clarity desplegados específicos que valen la pena mencionar." + } +} diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..62c7c60462 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: Contrato BNS +description: El Sistema de Nombres de Bitcoin. +--- + +![](/img/satoshi-btc.png) + +## Introducción + +El Sistema de Nombres Bitcoin (Bitcoin Name System, en inglés abreviado como BNS) se implementa como un contrato inteligente usando Clarity. + +A continuación se muestra una lista de funciones públicas y de solo lectura, así como los códigos de error que pueden devolver esos métodos: + +- [Funciones públicas](#public-functions) +- [Funciones de solo lectura](#read-only-functions) +- [Códigos de error](#error-codes) + +## Funciones públicas + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Descripción: + +Importa un nombre a un namespace revelado. A cada nombre importado se le asigna tanto un propietario como un estado off-chain. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Descripción: + +Reserva un nombre informando a todos los nodos de BNS el hash salt del nombre de BNS. Se paga la tarifa de registro a la dirección designada por el propietario del namespace. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Descripción: + +Revela el salt y el nombre a todos los nodos BNS, y asigna a el nombre un hash de clave pública inicial y un hash del archivo de zona. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Descripción: + +Dependiendo de las reglas del namespace, un nombre puede expirar. Por ejemplo, los nombres en el namespace .id expiran después de 2 años. Necesitas enviar una renovación de nombre de vez en cuando para mantener tu nombre. + +Pagará el coste de registro de su nombre a la dirección de grabación designada por el namespace cuando lo renueve. Cuando un nombre caduca, ingresa a un \"período de gracia\". El período está fijado en 5000 bloques (un mes) pero puede configurarse para cada namespace. + +Dejará de resolverse en el período de gracia, y todas las operaciones anteriores dejarán de ser reconocidas por las reglas de consenso de BNS. Sin embargo, puede enviar un NAME_RENEWAL durante este período de gracia para preservar su nombre. Después del período de gracia, cualquier persona puede registrar ese nombre nuevamente. Si su nombre está en un namespace donde los nombres no caducan, entonces nunca necesitará usar esta transacción. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Descripción: + +Hace que un nombre no se pueda resolver. Las reglas de consenso de BNS estipulan que una vez que se revoca un nombre, nadie puede cambiar su hash de clave pública ni su hash de archivo de zona. El hash del archivo de zona del nombre se establece en nulo para evitar que se resuelva. Deberías hacer esto solo si tu clave privada ha sido comprometida, o si deseas que tu nombre no se pueda usar por alguna razón. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Descripción: + +Cambia el hash de clave pública del nombre. Enviarías una transacción de transferencia de nombre si quisieras: + +- Cambiar tu llave privada +- Enviar el nombre a otra persona o +- Actualizar tu archivo de zona + +Al transferir un nombre, tienes la opción de también borrar el hash del archivo de zona del nombre (es decir, establecerlo en nulo). Esto es útil cuando envías el nombre a otra persona, para que el nombre del destinatario no resuelva a tu archivo de zona. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Descripción: + +Cambia el hash del archivo de zona del nombre. Enviarías una transacción de actualización de nombre si quisieras cambiar el contenido del archivo de la zona del nombre. Por ejemplo, harías esto si quieres desplegar tu propio hub de Gaia y deseas que otras personas lean desde él. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Descripción: + +Registra el hash salted del namespace con los nodos de BNS y quema la cantidad requerida de criptomoneda. Además, este paso demuestra a los nodos de BNS que el usuario ha respetado las reglas de consenso de BNS al incluir un hash de consenso reciente en la transacción. Devuelve la fecha de vencimiento del pre-pedido (en bloques). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Descripción: + +Lanza el namespace y lo hace disponible al público. Una vez que se lanza un namespace, cualquiera puede registrar un nombre en él si paga la cantidad apropiada de criptomonedas. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Descripción: + +Revela el salt y el ID del namespace (después de una preo orden del namespace). Muestra cuánto tiempo duran los nombres en este namespace antes de que caduquen o deban ser renovados, y establece una función de precio para el namespace que determina cuán barato o caro serán sus nombres. Todos los parámetros prefijados por `p` componen la `price function`. Estos parámetros rigen el precio y el tiempo de vida de los nombres en el namespace. + +Las reglas para un namespace son las siguientes: + +- un nombre puede caer en uno de los 16 buckets, medidos por longitud. El bucket 16 incorpora todos los nombres al menos de 16 caracteres de longitud. + +- la estructura de precios aplica una penalización multiplicativa por tener caracteres numéricos, o caracteres de puntuación. + +- el precio de un nombre en un bucket es `((coeff) * (base) ^ (exponente del bucket)) / ((multiplicador de descuento numérico) * (multiplicador de descuento de puntuación))` + +Ejemplo: + +- base = 10 +- coeff = 2 +- descuento nonalpha: 10 +- descuento no-vocal: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Funciones de solo lectura + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Descripción: + +Devuelve verdadero si el nombre proporcionado puede ser registrado. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Descripción: + +Devuelve verdadero si el namespace proporcionado está disponible. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Descripción: + +Devuelve verdadero si el nombre proporcionado puede ser recibido. Es decir, si actualmente no está en propiedad de alguien, un arrendamiento anterior ha caducado y el nombre no ha sido revocado. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Descripción: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Descripción: + +Obtiene el precio de un namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Descripción: + +Obtener propiedades del namespace. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Descripción: + +Devuelve verdadero si el contrato de arrendamiento del nombre proporcionado ha caducado. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Descripción: + +Obtener detalles de registro de nombres. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Descripción: + +Devuelve el nombre registrado que posee un principal si existe alguno. Un principal solo puede poseer un nombre a la vez. + +## Códigos de error + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6781a74896 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introducción + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +A continuación se muestra una lista de funciones públicas y de solo lectura, así como los códigos de error que pueden devolver esos métodos: + +- [Funciones públicas](#public-functions) +- [Funciones de solo lectura](#read-only-functions) +- [Códigos de error](#error-codes) + +## Funciones públicas + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### descripción: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### descripción: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### descripción: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### descripción: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### descripción: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### descripción: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### descripción: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### descripción: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Funciones de solo lectura + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### descripción: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### descripción: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### descripción: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### descripción: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### descripción: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### entrada: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### descripción: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### entrada: `uint` + +#### salida: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### descripción: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Códigos de error + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..da5d9732a6 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introducción + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/es/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/es/docusaurus-plugin-content-docs/current/contribute/docs.md index d28e84d26c..afd2fd65af 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Aprende cómo se construye este sitio y cómo puedes contribuir a Gracias por su interés en contribuir y ayudar a que estos documentos sean tan buenos como puedan ser. -Este sitio de documentación está construido en la plataforma de código abierto [Discosaurus 2](https://docusaurus.io/) y la mayor parte de su contenido está escrito en archivos Markdown. Todo el código para este sitio es libre y de código abierto, ubicado en el [repositorio de GitHub aquí](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. Todo el código para este sitio es libre y de código abierto, ubicado en el [repositorio de GitHub aquí](https://github.com/stacks-network/docs). :::tip ¿No sabes qué es Markdown? ¿Quieres aprender? Aquí hay una [guía útil](https://guides.github.com/features/mastering-markdown/) para aprenderlo. @@ -15,7 +15,7 @@ Este sitio de documentación está construido en la plataforma de código abiert :::info Necesitas una cuenta gratuita en [GitHub](https://www.github.com) para añadir o editar cualquier contenido. ::: -Para editar cualquier página, solo haga clic en el botón *Editar esta página* en la parte inferior de cada página y envíe sus cambios en línea. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. Para añadir nuevo contenido, existen dos formas diferentes de hacerlo, la [forma fácil](#easy-way) y la [forma avanzada](#advanced-way). @@ -24,28 +24,32 @@ Para añadir nuevo contenido, existen dos formas diferentes de hacerlo, la [form [**Simplemente haga clic aquí e ingrese el texto del artículo que desea añadir.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) Esto abrirá una observación en github usando nuestra plantilla. + ## Forma avanzada Para cambios más avanzados puede seguir los siguientes pasos. También puede probar el sitio localmente utilizando este método. + ### Pasos -1. Haga un Fork del [repositorio de documentos](https://github.com/stacks-network/docs) haciendo clic en el botón *Fork* en la parte superior derecha de la pantalla. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clona el fork a tu máquina local con este comando `git clone git@github.com:/docs.git stacks_docs` 3. Entre a la carpeta del proyecto `cd stacks_docs` 4. Crea una rama `git checkout -b feat/my-feature-branch`. 5. Opcionalmente puede previsualizar sus cambios en tiempo real con: - - `npm install` (para instalar dependencias). - - `npx docusaurus start` para iniciar una copia local del sitio. Un navegador web se abrirá en http://localhost:3000, para que pueda ver una vista previa de sus cambios en tiempo real. + - `npm install` (para instalar dependencias). + - `npx docusaurus start` para iniciar una copia local del sitio. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Haga los cambios que desee y luego haga un commit con este tipo de mensaje: `git commit -am "feat: some new feature or content"`. 7. Haga Push a Github con `git push --set-upstream origin feature/my-feature-branch`. 8. Visite GitHub y haga su pull request. -## Información adicional +## Additional information + ### Ejecutando y construyendo el sitio en local (opcional) Puedes iniciar la página en local con el siguiente comando. Esto es suficiente para previsualizar tus cambios. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Antes de ejecutar este comando por primera vez, debes de ejecutar `npm install` La página de docs será accesible en la siguiente url: [`http://localhost:3000`](http://localhost:3000). - Una vez finalizados los cambios, puedes construir un site entero con el siguiente comando (normalmente no es necesario): + ```bash npm run build ``` @@ -91,7 +95,7 @@ Todos los documentos en inglés se almacenan en la carpeta `/docs/`. Para añadir nuevos contenidos en inglés simplemente agregue un archivo markdown (.md) en cualquier subcarpeta en docs, y se mostrará automáticamente en la categoría de esa carpeta. -Todos los documentos en otros idiomas se almacenan bajo la carpeta `i18n`, pero estos archivos nunca deben editarse usando GitHub, ya que son sobrescritos por Crowdin cada vez que se agregan nuevas traducciones. **Para hacer cambios en otros idiomas**, debes hacerlo usando Crowdin. Por favor, consulta [traducciones](translations) en su lugar. +Todos los documentos en otros idiomas se almacenan bajo la carpeta `i18n`, pero estos archivos nunca deben editarse usando GitHub, ya que son sobrescritos por Crowdin cada vez que se agregan nuevas traducciones. **Para hacer cambios en otros idiomas**, debes hacerlo usando Crowdin. Por favor, consulta [traducciones](translations) en su lugar. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Usar "Commits Convencionales" Utilizamos los [Commits Convencionales](https://www.conventionalcommits.org/en/v1.0.0/) y la convención de nombres de commits. Utilízalo mientras contribuyes, por favor. @@ -138,6 +143,7 @@ Para escribir un bloque de código, necesitas envolver tu código en ` ```langua (define-public (get-counter) (ok (var-get counter))) ``` + ### Avisos Puede utilizar los siguientes avisos para resaltar el contenido. @@ -204,4 +210,4 @@ Algo de **contenido** con `syntax` markdown. Algo de **contenido** con `syntax` markdown. -::: \ No newline at end of file +::: diff --git a/i18n/es/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/es/docusaurus-plugin-content-docs/current/contribute/translations.md index 0391e7e386..b31b326c31 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribuye en la traducción -description: '¿Quieres ayudar a traducir la documentación a tu propio idioma?' +description: Want to help translating these docs to your local language? --- ## Ayuda con las traducciones -Las traducciones se gestionan con Crowdin. -Cualquiera puede colaborar y no se requieren habilidades técnicas, ya que todo se hace en el navegador. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. Para ayudarte con la traducción, ve a [esta página](https://crowdin.com/project/docsstacksco), haz clic en cualquier idioma y empieza a traducir. Toda ayuda es bienvenida. :::caution -Por favor, no añadas ninguna traducción al repositorio de Github, ya que las páginas traducidas son reescritas desde Crowdin. Es necesario añadir las traducciones en Crodin en vez. +Por favor, no añadas ninguna traducción al repositorio de Github, ya que las páginas traducidas son reescritas desde Crowdin. Translations need to be added on Crowdin instead. ::: ### Problemas comunes en las traducciones Al traducir en Crowdin, por favor traduce los textos y no el código html. -Si accidentalmente modificas las etiquetas html, obtendrás errores como los que se muestran a continuación (`Seems like some formating tags are missing` o `Translation contains tag that source text doesn't have`). Estos errores evitarán que tu traducción se publique hasta que las etiquetas se dejen como en el texto original. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). Estos errores evitarán que tu traducción se publique hasta que las etiquetas se dejen como en el texto original. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/es/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index e938409343..4bc5111559 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Utilice un enlace en la tabla para lanzar la plantilla [CloudFormation](https:// ### Paso 2 - Configurar stack usando la plantilla -Debe configurar la plantilla con los valores adecuados para su hub y el dominio en el que se ejecuta. +You need to configure the template with the appropriate values for your hub and domain it runs on. Seleccione `Template is ready` y `Amazon S3 URL` e introduzca la siguiente URL de Amazon S3: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Especifique los detalles de stacks y luego haga clic en `Next`: ![Especificar pl | EmailAddress | _tu dirección de correo electrónico_ | | | GaiaBucketName | _S3 bucket name_ | La plantilla combina este nombre con el nombre del stack para crear un bucket de S3 único. La plantilla ignora este campo si GaiaStorageType está establecido en `disk`. | | GaiaStorageType | `s3` o `disk` | Seleccione el GaiaStorageType que se utilizará como un backend para el Hub de Gaia. Seleccionar `s3` hace que la plantilla cree un bucket de S3 basado en el nombre dado en el campo anterior. Al seleccionar `disk`, la plantilla adjunta un volumen EBS independiente a la instancia EC2 para el almacenamiento del Hub. | -| InstaceType | t2.micro | Seleccione el tipo de instancia que desee. El valor predeterminado es `t2.micro`. | +| InstanceType | t2.micro | Seleccione el tipo de instancia que desee. El valor predeterminado es `t2.micro`. | | KeyName | | En la lista desplegable KeyName selecciona un [EC2 KeyPair](https://console. aws. amazon. com/ec2/v2/home? region=us-east-1#KeyPairs:) para habilitar el acceso SSH a la instancia EC2. Deberías descargar el archivo keyfile `.pem` para este par desde la consola EC2. Para más información vea la [documentación de EC2 key pair](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Deje el campo SSHLocation con el valor predeterminado de `0.0.0.0/0` para habilitar el acceso SSH desde cualquier dirección IP. Si desea restringir el acceso SSH a la instancia de EC2 a una determinada IP, puede actualizar este campo. | | SubnetId | _subnetId_ | Seleccione una subred pública | @@ -93,7 +94,9 @@ ssh -i admin@ Abra sus VPCs Seleccione su VPC conectado a su Gaia Hub Haga clic en `Acciones` -> `Editar nombres de host DNS` -> Cambie `nombres de host DNS` a `Activar` + ::: + ## Representación gráfica de la plantilla de cloudformation -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/es/docusaurus-plugin-content-docs/current/gaia/gaia.md index 908fe80039..5352be6c51 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Arquitectura de almacenamiento descentralizado para datos fuera de la cadena -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introducción -Las aplicaciones construidas en la blockchain de Stacks almacenan datos fuera de cadena usando un sistema de almacenamiento llamado Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Mientras que los metadatos transaccionales públicos se almacenan mejor en la blockchain de Stacks, los datos de las aplicaciones de los usuarios pueden almacenarse a menudo de forma más eficiente y privada en el almacenamiento de Gaia. @@ -38,7 +44,7 @@ La blockchain de Stacks almacena sólo datos de identidad. Los datos creados por Un hub de Gaia funciona como un servicio que escribe en el almacenamiento de datos. El almacenamiento en sí mismo es un simple almacén clave-valor. El servicio del Hub escribe en el almacenamiento de datos requiriendo un token de autenticación válido de un solicitante. Por lo general, el servicio del Hub se ejecuta en un recurso de cómputo y el almacenamiento propiamente dicho en un recurso de almacenamiento dedicado y separado. Por lo general, ambos recursos pertenecen al mismo proveedor de computación en la nube. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) El enfoque de Gaia hacia la descentralización se centra en el control de los datos por parte del usuario y su almacenamiento. Los usuarios pueden elegir un proveedor de Hub de Gaia. Si un usuario puede elegir qué proveedor de hub de Gaia utilizar, entonces esa opción es toda la descentralización necesaria para permitir aplicaciones controladas por el usuario. Además, Gaia define una API uniforme para aplicaciones para acceder a esos datos. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/es/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index f98f5b84e3..433d1de79d 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Pasos para configurar un hub GAIA en un servidor Linux (instalación nueva). Este ejemplo está usando Debian, pero debería funcionar en cualquier distribución de Linux. Utiliza docker compose por detras. +description: Pasos para configurar un hub GAIA en un servidor Linux (instalación nueva). Este ejemplo está usando Debian, pero debería funcionar en cualquier distribución de Linux. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ Esta configuración configurará los siguientes 4 contenedores docker: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Instala [docker](https://docs.docker.com/engine/install/debian/) y [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** en tu sistema operativo. -Para nuestro ejemplo instalamos _docker_ con: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copia y edita el archivo .env appropiado**. -En la carpeta `. deploy/docker/` son archivos de ejemplo diferentes para diferentes configuraciones como el uso de aws, azure o disco entre otros. En este ejemplo almacenaremos los datos localmente para que copiemos el archivo _de disco_ y actualicemos el dominio y los campos de correo electrónico. Por favor, cambie `gaia.site.com` y `gaiarocks@mydomain.com` como corresponda. Tenga en cuenta que necesita ambos para que el certificado SSL se cree correctamente. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Por favor, cambie `gaia.site.com` y `gaiarocks@mydomain.com` como corresponda. Tenga en cuenta que necesita ambos para que el certificado SSL se cree correctamente. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/es/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/es/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/intro.md b/i18n/es/docusaurus-plugin-content-docs/current/intro.md index 8716696a0a..9ebbf5aab9 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Inicio" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Introducción de la documentación de Stacks +# Stacks Docs -Bienvenido a la documentación oficial de Stacks impulsada por la comunidad. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Aprende sobre el minado de Stacks, el token STX y el lenguaje de programación de contratos inteligentes, Clarity. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodos y Mineros + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/es/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/es/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index 1d3d2b2d28..8b945979d0 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks en DigitalOcean +title: Run a Node with Digital Ocean description: Una guía para configurar Stacks en DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introducción -Esta es una guía paso a paso para desplegar el [Stacks Blockchain en DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). El código está alojado en este [repositorio de Github](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Pasos #### Paso 1 -Vaya a la página [Stacks Blockchain](https://marketplace.digitalocean.com/apps/stacks-blockchain) en el mercado de DigitalOcean. Haga clic en `Create Stacks Blockchain Droplet`. +Vaya a la página [Stacks Blockchain](https://marketplace.digitalocean.com/apps/stacks-blockchain) en el mercado de DigitalOcean. Haga clic en `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Paso 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Paso 3 -Introduzca una contraseña de root o active las claves SSH si lo prefiere. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Necesitarás esperar unos segundos para que el droplet se cree. Una vez creado h ## Empezando después de desplegar Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. -To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. +Para hacer un seguimiento del progreso, puedes hacer `root@your_droplet_public_ipv4` al host y ejecutar: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` para acceder a los datos directamente, siendo la salida similar a: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` -All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + +Todos los servicios son administrados por un [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) que está configurado para comenzar al arrancar. + +El control manual también es posible a través del script [manage.sh](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) en `/opt/stacks-blockchain-docker/manage.sh` en el host. -Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +## Launching a Droplet using the DigitalOcean API -## Creación de API +Además de crear un Droplet desde la aplicación de Stacks Blockchain 1-Click a través del panel de control, también puedes usar la [API de DigitalOcean](https://digitalocean.com/docs/api). -In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). +Como ejemplo, para crear un Droplet de 4GB Stacks Blockchain en la región SFO2, puede utilizar el siguiente comando curl. Tendrás que guardar tu [token de acceso a la API](https://docs.digitalocean.com/reference/api/create-personal-access-token/) en una variable de entorno o sustituirlo en el siguiente comando. -As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index f25944c2c5..8cdc5506da 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodos y Mineros description: Nodos y Mineros -sidebar_position: 7 +sidebar_position: 5 --- -Aquí están todos los pasos para ejecutar nodos y mineros, tanto en mainnet como en testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## ¿Qué es un nodo de Stacks? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## ¿Qué es un minero de Stacks? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..950db7fa52 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -1,6 +1,6 @@ --- -title: Miner costs and fees -description: Miner Cost and Fee Estimation +title: Costes de Minería y Estimación de comisiones +description: Costes de Minería y Estimación de comisiones sidebar_position: 8 --- @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 3c74e8bd03..1fce8a27a6 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introducción -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Finally, start bitcoind as follows: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. +Next, update the bitcoin configuration: -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Running a miner in Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Pre requisitos +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Generate keychain and get mainnet tokens in Windows +### Generate a keychain -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Update the following properties: +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -313,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index f1a8345c66..510246467c 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introducción -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Pre requisitos +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -324,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..7a7836f90e 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuración](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index ea61c808e0..fe42ce8478 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Configuración del nodo de Stacks description: Parámetros de configuración y opciones para el binario stacks-node -sidebar_position: 6 +sidebar_position: 4 --- ## Uso @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcomandos +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Los comandos obsoletos pueden ser accesibles hasta que sean eliminados completamente del código fuente. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Opciones de configuración -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Ejemplo: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Ejemplo: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Descripción | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Ejemplo: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Descripción | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Ejemplo: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Argumentos +| Name | Required | Descripción | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Ejemplo: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Descripción | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Minería -#### version +| Name | Required | Descripción | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Muestra información sobre la versión actual y el ciclo de lanzamiento. +### ustx_balance -Ejemplo: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Muestra un mensaje de ayuda. +:::info This section is only required for the `testnet` and `mocknet` networks. -Ejemplo: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Descripción | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Opciones de configuración +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Sección: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Ejemplo: + diff --git a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/es/docusaurus-plugin-content-docs/current/references/glossary.md index 0099a439aa..9908acdef7 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: Una lista de términos comunmente utilizados en el ecosistema. Una lista de términos comunmente utilizados en el ecosistema. -#### Revisiones de Aplicación -Un mecanismo de incentivos para los desarrolladores de aplicaciones en la fase inicial (primeros cuatro años) del ecosistema y para impulsar el autodesarrollo del mercado. - #### Atlas Una red de pares proporciona un índice global para su descubrimiento. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### bloque +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO Ver Organización Autónoma Desdentralizada. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Organización Autónoma Descentralizada (DAO) A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### firma digital +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### bloque génesis +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identidad - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### red de malla +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### minería +#### Minería Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### nombre +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Token no fungible. -#### llave privada +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### clave pública +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### Frase semilla +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### contrato inteligente +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Monedero de Stacks An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). More information and example [here](../services-using-stacks/wallets). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transacción +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### blockchain virtual -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index c4a1864f64..58717a3234 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -1,13 +1,13 @@ --- title: DeFi -description: Sitios De-Fi en Stacks +description: De-Fi sites on Stacks sidebar_position: 2 --- They are multiple De-Fi sites that operate on the Stacks blockchain. -:::tip ¿Falta uno? -Por favor edita esta página para agregar cualquier sitio web relevante que falte. +:::tip Are we missing one? +Please edit this page to add any relevant new site that we are missing. ::: ## Alex @@ -20,13 +20,13 @@ Por favor edita esta página para agregar cualquier sitio web relevante que falt ## Catamaran Swaps -[Catamaran Swaps](https://www.catamaranswaps.org/) permite el intercambio de activos digitales sin requirimiento de confianza. +[Catamaran Swaps](https://www.catamaranswaps.org/) allows trustless exchange of digital assets. ![](/img/sh_catamaran.png) ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Por favor edita esta página para agregar cualquier sitio web relevante que falt [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index e28ff4727e..1e14b9a5a5 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -1,13 +1,13 @@ --- -title: Más -description: Más servicios construidos en Stacks. +title: More +description: More services built on Stacks. sidebar_position: 5 --- -Lista de sitios añadidos por la comunidad en orden alfabético. +List of sites on alphabetical order added by the community. -:::tip ¿Falta uno? -Por favor edita esta página para agregar cualquier sitio web relevante que falte. +:::tip Are we missing one? +Please edit this page to add any relevant new site that we are missing. ::: ## Citycoins @@ -18,6 +18,6 @@ Por favor edita esta página para agregar cualquier sitio web relevante que falt ## Sigle -[Sigle](https://www.sigle.io/) es una plataforma de escritura web 3 descentralizada y de código abierto. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index d24c66ba1e..d582604854 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -1,30 +1,39 @@ --- title: NFTs -description: NFTs en Stacks +description: NFTs on Stacks sidebar_position: 3 --- -Lista de sitios web que operan NFTS en Stacks en orden alfabético. +List of sites that operate NFTS on Stacks on alphabetical order. -:::tip ¿Falta uno? -Por favor edita esta página para agregar cualquier sitio web relevante que falte. +:::tip Are we missing one? +Please edit this page to add any relevant new site that we are missing. ::: ### [Byzantion](https://byzantion.xyz/) -![captura de pantalla de página web](/img/sh_nft_byzantion.png) +![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) -![captura de pantalla de página web](/img/sh_nft_gamma.png) + +![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) -![captura de pantalla de página web](/img/sh_nft_megapont.png) +![website-screenshot](/img/sh_nft_megapont.png) + +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) ### [StacksArt](https://www.stacksart.com/) -![captura de pantalla de página web](/img/sh_nft_stacksart.png) +![website-screenshot](/img/sh_nft_stacksart.png) + +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 180d2da19d..54f6823e33 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -1,13 +1,13 @@ --- -title: Sitios web con información Stacks +title: Stacks info sites description: Status and stats of the Stacks network. sidebar_position: 1 --- -Un listado de sitios web en orden alfabético con muestran el estado y estadísticas de la red Stacks. +A list of sites on alphabetical order that display status and stats of the Stacks network. -:::tip ¿Falta uno? -Por favor edita esta página para agregar cualquier sitio web relevante que falte. +:::tip Are we missing one? +Please edit this page to add any relevant new site that we are missing. ::: ### [Haystack](https://haystack.tools/mempool) @@ -30,7 +30,7 @@ Por favor edita esta página para agregar cualquier sitio web relevante que falt ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index 9e9b57ec76..de4f9339e7 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -1,13 +1,13 @@ --- -title: Wallets -description: Wallets para Stacks +title: Billeteras +description: Wallets for Stacks sidebar_position: 4 --- -Un listado de wallets de hardware y software para Stacks +A list of hardware and software wallets for Stacks -:::tip ¿Falta uno? -Por favor edita esta página para agregar cualquier sitio web relevante que falte. +:::tip Are we missing one? +Please edit this page to add any relevant new site that we are missing. ::: ## Blockchain.com @@ -15,6 +15,7 @@ Por favor edita esta página para agregar cualquier sitio web relevante que falt [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Por favor edita esta página para agregar cualquier sitio web relevante que falt [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Por favor edita esta página para agregar cualquier sitio web relevante que falt [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..21a4d17ac4 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Cuentas +description: Guía de cuentas de Stacks 2.0 +sidebar_position: 7 +--- + +## Introducción + +Las cuentas Stacks 2.0 son entidades que poseen assets, como los tokens de Stacks (STX). Una cuenta contiene una dirección, clave privada, un nonce, y uno o más saldos de activos. + +:::tip El algoritmo de cifrado utilizado en Stacks 2.0 es **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Adicionalmente, [Ed25519](https://ed25519.cr.yp.to/) también se utiliza solo para la VRF (función aleatoria verificable). ::: + +Los assets no pueden dejar una cuenta sin una acción del propietario de la cuenta. Todos los cambios en los assets (y los saldos de la cuenta) requieren una transacción correspondiente. + +:::tip +El tipo de transacción no necesita ser una transferencia de tokens - el deploy del contrato y las llamadas de contrato pueden cambiar los balances de una cuenta +::: + +## Creación + +Una cuenta se genera a partir de una frase mnemónica de 24 palabras. Esto a menudo se le conoce como **la frase semilla**. La frase semilla proporciona acceso a las cuentas Stacks 2.0. + +:::danger +Si la frase de semilla se pierde, el acceso a la cuenta asociada no se puede recuperar. No person or organization can recover a lost seed phrase. +::: + +La forma más fácil de generar una nueva cuenta de Stacks 2.0 es utilizar la [CLI de Stacks](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# instalar CLI globalmente +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` crea la siguiente línea: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Campo | Descripción | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mnemonic` | Una frase semilla de 24 palabras utilizada para acceder a la cuenta, generada usando [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) con 256 bits de entropía | +| `keyInfo.privateKey` | Clave privada para la cuenta. Requerida para transferencias de tokens y a menudo llamada como `senderKey` | +| `keyInfo.address` | Dirección Stack para la cuenta | +| `keyInfo.btcAddress` | Dirección BTC correspondiente para la cuenta. | +| `keyInfo.wif` | Clave privada de btcAddress en formato comprimido. | +| `keyInfo.index` | Nonce para la cuenta, iniciando en 0 | + +Ten en cuenta que existe una nueva cuenta automáticamente para cada nueva clave privada. No hay necesidad de instanciar manualmente una cuenta en la blockchain Stacks 2.0. + +:::tip Las direcciones se crean generando el [hash RIPEMD-160](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) del [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) de la clave pública. Las direcciones BTC están codificadas con [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). Para direcciones Stacks, se utiliza [c32check](https://github.com/stacks-network/c32check). Se puede obtener una dirección de una clave pública sin acceso a Internet, por ejemplo utilizando el método c32check `c32addressDecode`. ::: + +Alternativamente a la creación con CLI, se puede utilizar la librería [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions): + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +Una segunda alternativa sería utilizar [stacks-gen](https://github.com/psq/stacks-gen). Esta herramienta generará todas las claves que necesita en un solo lugar, incluyendo los valores necesarios para llamar al contrato de staking, y también una clave WIF para usar con `bitcoind`. + +#### prerrequisito de stacks-gen + +Instalar [npx](https://github.com/npm/npx) si no está instalado. (npx comprobará si `` existe en \$PATH, o en los binarios locales del proyecto y lo ejecuta. Si `` no se encuentra, se instalará antes de la ejecución). + +``` +npm install -g npx +``` + +#### uso de stacks-gen + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip El objeto stacking con hashbytes y una versión representa la dirección bitcoin derivada de la dirección de pilas. Lea más sobre el [formato de dirección bitcoin](stacking#bitcoin-address). ::: + +La documentación completa está disponible en [stacks-gen](https://github.com/psq/stacks-gen). + +## Consultas + +### Obtener el balance de Stacks (STX) y nonce + +El saldo STX y nonce se pueden obtener a través del endpoint [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info): + +```bash +# para mainnet, reemplazar `testnet` por `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Ejemplo de respuesta: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +La cadena de balance representa un entero sin signo de 128-bit (big-endian) en codificación hexadecimal +::: + +### Obtener los balances de todos los tokens + +Todos los balances de tokens se pueden obtener a través del endpoint [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance): + +```bash +# para mainnet, reemplazar `testnet` por `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Ejemplo de respuesta: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Las cuentas Stacks no pueden contener bitcoins. La mejor manera de obtener los balances BTC correspondientes es derivar la dirección BTC de la dirección Stacks (usando [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) y consultar la red Bitcoin. ::: + +### Obtener todos los eventos de los asset + +Todos los eventos de asset asociados con la cuenta se pueden obtener a través del endpoint [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance): + +```bash +# para mainnet, reemplazar `testnet` por `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Ejemplo de respuesta: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..ae4363179c --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Autenticación +description: Registrar e iniciar sesión de usuarios con identidades en la blockchain de Stacks +sidebar_position: 8 +--- + +## Introducción + +Esta guía explica cómo se realiza la autenticación en el blockchain de Stacks. + +La autenticación proporciona una forma para que los usuarios se identifiquen a sí mismos en una aplicación mientras conservan el control total sobre sus credenciales y datos personales. Puede integrarse solo o utilizarse en conjunto con [la firma de transacciones](https://docs.hiro.so/get-started/transactions#signature-and-verification) y [el almacenamiento de datos](https://docs.stacks.co/gaia/overview), para lo cual es un requisito previo. + +Los usuarios que se registren en su aplicación pueden autenticarse posteriormente en cualquier otra aplicación con soporte para el [Blockchain Naming System (BNS)](bns) y viceversa. + +## Cómo funciona + +El flujo de autenticación con Stacks es similar al típico flujo cliente-servidor utilizado por los servicios de registro centralizado (por ejemplo, OAuth). Sin embargo, con Stacks el flujo de autentificación ocurre enteramente del lado del cliente. + +La aplicación almacena la clave de tránsito efímera durante la generación de solicitudes. La parte pública de la clave de tránsito se pasa en el token `authRequest`. El autenticador utiliza la porción pública de la clave para cifrar una _clave privada de la aplicación_ que se devuelve a través del `authResponse`. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. Se pasan a través de URL query strings. + +Cuando un usuario elige autenticar una aplicación, envía el token `authRequest` al autenticador a través de una URL query string con un parámetro igualmente nombrado: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +Cuando el autenticador recibe la solicitud, genera un token `authResponse` para la aplicación usando una _clave de tránsito efímera_. La clave de tránsito efímera solo se utiliza para la instancia particular de la aplicación, en este caso, para firmar el `authRequest`. + +La aplicación almacena la clave de tránsito efímera durante la generación de solicitudes. La aplicación solicitante envía al autenticador un token `authRequest`. El autenticador utiliza la porción pública de la clave para cifrar una _clave privada de la aplicación_ que se devuelve a través del `authResponse`. + +El autenticador genera la clave privada de la aplicación desde _la clave privada de la dirección de identidad_ del usuario y el dominio de la aplicación. La clave privada de la aplicación cumple tres funciones: + +1. Se utiliza para crear credenciales que dan a la aplicación acceso a un bucket de almacenamiento en el hub de Gaia del usuario +2. Se utiliza en el cifrado de extremo a extremo de los archivos almacenados para la aplicación en el almacenamiento Gaia del usuario. +3. Sirve como un secreto criptográfico que las aplicaciones pueden usar para realizar otras funciones criptográficas. + +Por último, la clave privada de la aplicación es determinista, lo que significa que siempre se generará la misma clave privada para una dirección y un dominio de Stacks determinados. + +Las dos primeras de estas funciones son particularmente relevantes para el [almacenamiento de datos con Stacks.js](https://docs.stacks.co/docs/gaia). + +## Par de Claves + +La autenticación con Stacks hace un uso extensivo de la criptografía de clave pública en general y ECDSA con la curva `secp256k1` en particular. + +Las siguientes secciones describen los tres pares de claves públicas-privadas utilizados, incluyendo cómo se generan, dónde se utilizan y a quién se revelan las claves privadas. + +### Clave privada de tránsito + +La clave privada de tránsito es una clave efímera que se utiliza para cifrar los secretos que deben pasar del autenticador a la aplicación durante el proceso de autenticación. Es generado aleatoriamente por la aplicación al principio de la respuesta de autenticación. + +La clave pública que corresponde a la clave privada de tránsito está almacenada en un único elemento array en la clave `public_keys` del token de solicitud de autenticación. El autenticador encripta datos secretos como la clave privada de la aplicación utilizando esta clave pública y lo envía de vuelta a la aplicación cuando el usuario inició sesión en la aplicación. La clave privada de tránsito firma la solicitud de autenticación de la aplicación. + +### Clave privada de la dirección de identidad + +La clave privada de la dirección de identidad se deriva de la frase del llavero del usuario y es la clave privada del nombre de usuario de Stacks que el usuario elige utilizar para iniciar sesión a la aplicación. Es un secreto propiedad del usuario y nunca deja la instancia del autenticador del usuario. + +Esta clave privada firma el token de respuesta de autenticación para una aplicación para indicar que el usuario aprueba el inicio de sesión en esa aplicación. + +### Clave privada de la App + +La clave privada de la aplicación es una clave privada específica de la aplicación que es generada a partir de la clave privada de la dirección de identidad del usuario utilizando el `domain_name` como entrada. + +La clave privada de la aplicación es compartida de forma segura con la aplicación en cada autenticación, encriptada por el autenticador con la clave pública de tránsito. Debido a que la clave de tránsito sólo se almacena en el lado del cliente esto previene un ataque man-in-the-middle en el que un servidor o proveedor de Internet podría potencialmente espiar la clave privada de la aplicación. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..b5a60f8f4a --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,245 @@ +--- +title: Bitcoin Name System +description: Vincula los nombres de usuario de Stacks al estado off-chain +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +La V1 de la blockchain de Stacks implementó BNS a través de operaciones de nombre de primer orden. En la V2 de Stacks. BNS es implementado a través de un contrato inteligente cargado durante el bloque de génesis. + +Los nombres en BNS tienen tres propiedades: + +- **Los nombres son únicos a nivel global.** El protocolo no permite colisiones de nombres, y todos los nodos que se comportan correctamente resuelven un nombre dado al mismo estado. +- **Los nombres tienen un significado humano.** Cada nombre es elegido por su creador. +- **Los nombres tienen una propiedad sólida.** Sólo el propietario del nombre puede cambiar el estado al que se resuelve. Específicamente, un nombre es propiedad de una o varias claves privadas ECDSA. + +La blockchain de Stacks asegura que la vista del BNS de cada nodo está sincronizada para todos los demás nodos del mundo, por lo que las consultas en un nodo seran las mismas en otros nodos. Los nodos de la blockchain de Stacks permiten al propietario de un nombre enlazar hasta 40Kb de estado off-chain a su nombre, el cual será replicado a todos los demás nodos de blockchain de Stacks a través de una red P2P. + +La mayor consecuencia para los desarrolladores es que en BNS, el estado del nombre de lectura es rápido y barato, pero el estado del nombre de la escritura es lento y costoso. Esto es porque registrar y modificar nombres requiere que una o más transacciones sean enviadas a la cadena de bloques subyacente, y los nodos BNS no los procesarán hasta que estén suficientemente confirmados. Los usuarios y desarrolladores necesitan adquirir y gastar la criptomoneda solicitada (STX) para enviar transacciones BNS. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. Cuando buscas un sitio web, estás utilizando el Servicio de Nombre de Dominio para asociar el nombre de host a la dirección IP de su host. Cuando revisa una rama de Git, está usando su cliente Git para asociar el nombre de la rama a un commit hash. Cuando buscamos la clave PGP de alguien en un servidor de claves, esta asociando su clave ID a su clave pública. + +¿Qué tipo de cosas queremos que sean ciertas sobre los nombres? En BNS, los nombres son únicos globalmente, tienen significado humano y tienen una propiedad sólida. En BNS, los nombres son únicos globalmente, tienen significado humano y tienen una propiedad sólida. Sin embargo, si observas estos ejemplos, verás que cada uno de ellos solo garantiza _dos_ de estas propiedades. Esto limita lo útiles que pueden ser. + +- En DNS y redes sociales, los nombres son globalmente únicos y legibles, pero no tienen una propiedad sólida. El operador del sistema tiene la última palabra sobre a qué se asocia cada nombre. + + - **Problema**: Los clientes deben confiar en el sistema para hacer la elección correcta en cuanto a la asociación de un nombre determinado. Esto incluye confiar en que nadie más que los administradores del sistema pueden hacer estos cambios. + +- En Git, los nombres de ramas son legibles para el ser humano y tienen una propiedad sólida, pero no son únicos globalmente. Dos nodos Git diferentes pueden asociar el mismo nombre de rama a diferentes estados no relacionados del repositorio. + + - **Problema**: Dado que los nombres pueden referirse a estados conflictivos, los desarrolladores tienen que averiguar algún otro mecanismo para resolver ambigüedades. En el caso de Git, el usuario tiene que intervenir manualmente. + +- En PGP, los nombres son identificadores de clave. They are globally unique and cryptographically owned, but not human-readable. Los IDs de claves PGP se derivan de las claves a las que hacen referencia. + - **Problema**: Estos nombres son difíciles de recordar para la mayoría de los usuarios ya que no llevan información semántica relacionada con su uso en el sistema. + +Los nombres de BNS tienen las tres propiedades, y ninguno de estos problemas. Esto hace que sea una herramienta potente para construir todo tipo de aplicaciones de red. Con BNS, podemos hacer lo siguiente y más: + +- Construir servicios de nombre de dominios donde los nombres de host no puedan ser secuestrados. +- Construir plataformas de redes sociales donde los nombres de usuario no puedan ser robados por phishers. +- Construir sistemas de control de versiones donde las ramas del repositorio no entren en conflicto. +- Construir infraestructura de llaves públicas donde sea sencillo para los usuarios descubrir y recordar las claves de los demás. + +## Organización de los BNS + +Los nombres de BNS están organizados en una jerarquía de nombres global. Hay tres capas diferentes en esta jerarquía relacionadas con el nombramiento: + +- **Namespaces**. Estos son los nombres de nivel superior en la jerarquía. Una analogía con los namespaces de BNS son los DNS de dominios de nivel superior. Los namespaces de BNS existentes incluyen `.id`, `.podcast`, and `.helloworld`. Todos los otros nombres pertenecen exactamente a un namespace. Cualquiera puede crear un namespace, pero para que un namespace sea persistente, debe ser _publicado_ para que cualquiera pueda registrar nombres en él. Namespaces no son propiedad de sus creadores. + +- **Nombres BNS**. Son nombres cuyos registros se almacenan directamente en la blockchain. La propiedad y estado de estos nombres están controlados por el envío de transacciones de blockchain. Algunos ejemplos de nombres son `verified.podcast` and `muneeb.id`. Cualquiera puede crear un Nombre BNS, siempre y cuando el namespace que lo contenga ya exista. + +- **Subdominios BNS**. Estos son nombres cuyos registros se almacenan off-chain, pero están colectivamente anclados a la blockchain. La propiedad y el estado de estos nombres viven dentro de los datos de la red P2P. Mientras que los subdominios de BNS son propiedad de claves privadas separadas, el propietario de un nombre BNS debe difundir el estado de su subdominio. Algunos ejemplos de subdominios son `jude.personal.id` and `podsaveamerica.verified.podcast`. A diferencia de los namespace y los nombres de BNS, el estado de los subdominios BNS _no es_ parte de las reglas de consenso de la blockchain. + +Una matriz de comparación de características que resume las similitudes y diferencias entre estos objetos de nombre se presenta a continuación: + +| Características | **Namespaces** | **Nombres BNS** | **Subdominios BNS** | +| ------------------------------------------------ | -------------- | --------------- | ------------------- | +| Único a nivel global | X | X | X | +| Significado humano | X | X | X | +| Propiedad de una clave privada | | X | X | +| Cualquiera puede crearla | X | X | [1] | +| El propietario puede actualizar | | X | [1] | +| Estado alojado on-chain | X | X | | +| Estado alojado off-chain | | X | X | +| Comportamiento controlado por reglas de consenso | X | X | | +| Puede tener una fecha de vencimiento | | X | | + +[1] Requiere la cooperación de un propietario de nombre BNS para emitir sus transacciones + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +Controlan algunas propiedades de los nombres que contienen: + +- Qué tan caros son para registrarse +- Cuánto tiempo duran antes de que tengan que renovarse +- Quién (si hay alguien) recibe las tarifas de registro del nombre +- Quien tiene permitido crear el namespace con sus nombres iniciales. + +En el momento de escribir este artículo, el namespace de BNS más grande es el `.id`. Los nombres en el namespace `.id` están diseñados para resolver identidades de usuario. Los nombres cortos en `.id` son más caros que los nombres largos, y tienen que ser renovados por sus propietarios cada dos años. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +A diferencia del DNS, _cualquiera_ puede crear un namespace y establecer sus propiedades. Los namespaces se crean por orden de llegada, y una vez creados, duran para siempre. + +Sin embargo, crear un namespace no es gratis. El creador del namespace debe _quemar la criptomoneda_ para hacerlo. Cuanto más corto sea el espacio de nombres, más criptomoneda debe ser quemado (es decir, los namespace cortos son más valiosos que los namespace largos). Por ejemplo, le cuesta a Blockstack PBC 40 BTC crear el namespace `.id` en 2015 (en la transacción `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Los namespace pueden tener entre 1 y 19 caracteres de longitud y están compuestos por los caracteres `a-z`, `0-9`, `-`, y `_`. + +## Subdominios + +Los nombres de BNS tienen una propiedad sólida porque el propietario de su clave privada puede generar transacciones válidas que que actualizan el hash y el propietario de su archivo de zona. Sin embargo, esto tiene el coste de de exigir al propietario del nombre que pague por la transacción subyacente en la blockchain. Además, este enfoque limita la tasa de registros y operaciones de nombres BNS y operaciones al ancho de banda de las transacciones de la blockchain subyacente. + +BNS supera esto con los subdominios. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Al igual que sus contrapartes on-chain, los subdominios son globalmente únicos, tienen una propiedad sólida y son legibles por el ser humano. BNS les da su propio estado de nombre y claves públicas. A diferencia de los nombres on-chain, los subdominios pueden ser creados y gestionados económicamente, porque son emitidos a la red de BNS en lotes. Una sola transacción de la blockchain puede enviar hasta 120 operaciones de subdominio. + +Esto se logra almacenando registros de subdominios en los archivos de zona de nombres de BNS. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. Para transmitir el archivo de zonas, el propietario del nombre establece el nuevo hash del archivo de zona con una transacción de `NAME_UPDATE` y replica el archivo de zona. Esto, a su vez, replica todas las operaciones del subdominio que contiene, y ancla el conjunto de operaciones de subdominio a una transacción on-chain. Las reglas de consenso del nodo BNS aseguran que solo operaciones de subdominio válidas de transacciones _validas_ de `NAME_UPDATE` sean almacenadas. + +Por ejemplo, el nombre `verified.podcast` una vez escribió el hash del archivo de zona `247121450ca0e9af45e85a82e61cd525cd7ba023`, que es el hash del siguiente archivo de zona: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Cada registro `TXT` en este archivo de zona codifica una creación de subdominio. Por ejemplo, `1yeardaily.verified.podcast` resuelve a: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +Esta información fue extraída del `1yeardaily` `TXT` en el archivo de la zona para `verified.podcast`. + +### Ciclo de vida del subdominio + +Ten en cuenta que `1yeardaily.verified.podcast` tiene un hash de clave pública diferente (dirección) que `verified.podcast`. Un nodo BNS sólo procesará una operación de subdominio posterior en `1yeardaily.verified.podcast` si incluye una firma de la clave privada de esta dirección. `verified.podcast` no puede generar actualizaciones; sólo el propietario de `1yeardaily.verified.podcast` puede hacerlo. + +El ciclo de vida de un subdominio y sus operaciones se muestran en la Figura 2. + +``` + creación de Actualización de Transferencia de + Subdominio Subdominio Subdominio ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | firmado | owner="1Et..." | firmado | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (hash de V + archivo de zona ) ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figura 2: Vida útil del subdominio con respecto a las operaciones de nombre on-chain. Una nueva +operación de subdominio solo será aceptada si tiene un número posterior de "sequence=" +y una firma válida en "sig=" sobre el cuerpo de la transacción. El campo "sig=" +incluye tanto la clave pública como la firma, y la clave pública debe tener un hash con el campo +"addr=" de la operación de subdominio anterior. + +Las transacciones de creación de subdominio y transferencia de subdominio para +"cicero.res_publica.id" son emitidas por el propietario de "res_publica.id" +Las transacciones de creación de subdominio y transferencia de subdominio para +"cicero.res_publica.id" son emitidas por el propietario de "res_publica.id" +Sin embargo, cualquier nombre on-chain ("jude.id" en este caso) puede transmitir una actualización de subdominio +para "cicero.res_publica.id." +``` + +Las operaciones de subdominios se ordenan por número de secuencia, comenzando en 0. Cada nueva operación de subdominio debe incluir: + +- El siguiente número de secuencia +- La clave pública que tiene el hash de la dirección de la transacción del subdominio anterior +- Una firma de la clave privada correspondiente sobre toda la operación del subdominio. + +Si se descubren dos operaciones de subdominio correctamente firmadas pero en conflicto (es decir, tienen el mismo número de secuencia), se acepta el que ocurre antes en el historial de blockchain. Las operaciones de subdominio no válidas son ignoradas. + +Combinado, esto garantiza que un nodo BNS con todos los archivos de zona con las operaciones de un subdominio determinado será capaz de determinar la secuencia válida de transiciones de estado por la que ha pasado, y determinar el archivo de zona actual y el hash de la clave pública del subdominio. + +### Creación y gestión de subdominios + +A diferencia de un nombre on-chain, un propietario de subdominio necesita la ayuda del propietario del nombre on-chain para transmitir sus operaciones de subdominio. En particular: + +- Una transacción de creación de subdominios solo puede ser procesada por el propietario del nombre on-chain que comparte su sufijo. Por ejemplo, solo el dueño de `res_publica.id` puede transmitir transacciones de creación de subdominios para nombres de subdominio que terminan en `.res_publica.id`. +- Una transacción de transferencia de subdominio sólo puede ser emitida por el propietario del nombre on-chain que la creó. Por ejemplo, el dueño de `cicero.res_publica.id` necesita al dueño de `res_publica.id` para transmitir una transacción de transferencia de subdominio para cambiar la clave pública `cicero.res_publica.id`. +- Para enviar una creación de subdominio o transferencia de subdominio, todos los archivos de zona del propietario del nombre on-chain deben estar presentes en la red de Atlas. Esto permite al nodo BNS demostrar la _ausencia_ de cualquier operación conflictiva de creación y operaciones de transferencia de subdominios al procesar nuevos archivos de zona. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. Por ejemplo, el dueño de `verified.podcast` puede transmitir una transacción de actualización de subdominio creada por el dueño de `cicero.res_publica.id`. + +Dicho esto, para crear un subdominio, el dueño del subdominio genera una operación de creación de subdominios para el nombre deseado y lo otorhga al propietario del nombre on-chain. + +Una vez creado, un propietario de subdominio puede usar cualquier propietario de nombre on-chain para transmitir una operación de actualización de subdominios. Para hacerlo, generan y firman la operación de subdominio solicitada y se la dan a un propietario de nombre on-chain, quien luego lo empaqueta con otras operaciones de subdominio en un archivo de zona DNS y lo transmite a la red. + +Si el propietario del subdominio quiere cambiar la dirección de su subdominio, necesita firmar una operación de transferencia de subdominio y dársela al propietario del nombre on-chain que creó el subdominio. Luego lo empaquetan en un archivo de zona y lo transmiten. + +### Registros de subdominio + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +Los nombres de BNS son compatibles con el emergente protocolo de especificación para identificadores descentralizados (DIDs) [Fundación de la Identidad Descentralizada](http://identity. foundation). + +Cada nombre en BNS tiene un DID asociado. El formato DID para BNS es: + +```bash + did:stack:v0:{address}-{index} +``` + +Dónde: + +- `{address}` es un hash de clave pública on-chain (por ejemplo una dirección de Bitcoin). +- `{index}` se refiere al nombre `nth` esta dirección creada. + +Por ejemplo, el DID para `personal.id` es `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, porque el nombre `personal.id` fue el primer nombre creado por `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +Otro ejemplo, el DID para `jude.id` es `did:stack:v0:16EMaNw3pkn3v6f2BgnSs53zAKH4Q8YJg-1`. Aquí, la dirección `16EMaNw3pkn3v6f2BgnSs53zAKH4Q8YJg` había creado un nombre anterior históricamente anterior a esta (que parece ser `abcdefgh123456.id`). + +El propósito de un DID es proporcionar un identificador eterno para una clave pública. La clave pública puede cambiar, pero el DID no. + +La blockchain de Stacks implementa un método DID propio para ser compatible con otros sistemas que usan DIDs para la resolución de clave pública. In order for a DID to be resolvable, all of the following must be true for a name: + +- El nombre debe existir +- El hash del archivo de zona del nombre debe ser el hash de un archivo de zona DNS bien formado +- El archivo de zona DNS debe estar presente en los datos del nodo de Stacks. +- El archivo de zona DNS debe contener un registro de recursos de `URI` que apunta a un JSON Web Token firmado +- La clave pública que firmó el JSON Web Token (y está incluida con él) debe hacer hash a la dirección que posee el nombre + +No todos los nombres tendrán DIDs que resuelvan claves públicas. Sin embargo, los nombres creados por herramientas estándar sí que tendrán DIDs. + +Una API RESTful está en desarrollo. + +## DID Encoding for Subdomains + +Cada nombre y subdominio en BNS tiene un DID. La codificación es ligeramente diferente para los subdominios, por lo que el software puede determinar qué code-path tomar. + +- Para nombres BNS on-chain, la `{address}` es la misma que la dirección Bitcoin que posee el nombre. Actualmente, las dirección tanto del byte de la versión 0 como del byte de la versión 5 son soportadas (es decir, direcciones que empiezan con `1` o `3`, significando `p2pkh` y `p2sh` direcciones). + +- Para subdominios BNS off-chain, el `{address}` tiene la versión del byte 63 para subdominios propiedad de una sola clave privada, y la versión 50 del byte para subdominios propiedad de un conjunto m-of-n de claves privadas. Es decir, las direcciones DID de subdominio comienzan con `S` o `M`, respectivamente. + +El campo `{index}` para el DID de un subdominio es distinto del campo `{index}` para el DID de un nombre BNS, incluso si el mismo creó nombres y subdominios. Por ejemplo, el nombre `abcdefgh123456. d` tiene el DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSs53zAKH4Q8YJg-0`, porque era el primer nombre creado por `16EMaNw3pkn3v6f2BgnSs53zAKH4Q8YJg`. Sin embargo, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _también_ creó `jude.statism.id` como su primer nombre de subdominio. El DID para `jude.statism.id` es `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Tenga en cuenta que la dirección `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i`codifica el mismo hash de clave pública que la dirección `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (la única diferencia entre estos dos strings es que la primera está codificada en base58checkcon la versión byte 0, y el segundo está codificado con la versión byte 63). diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..39e1503af5 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microbloques +description: Guía de Microbloques Stacks +sidebar_position: 5 +--- + +## Introducción + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Estados de la transacción + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +La transacción 1 se transmite al mempool. Tiene 0 confirmaciones. +La transacción 1 está incluida en un microbloque. Todavía tiene 0 confirmaciones, pero los resultados de la transacción son conocidos +La transacción 1 está incluida en el próximo bloque de anclaje. Tiene 1 confirmación. +El próximo bloque de Stacks confirma el bloque anterior. La transacción 1 tiene 2 confirmaciones. +El próximo bloque de Stacks confirma el bloque anterior. La transacción 1 tiene 3 confirmaciones. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +La transacción 2 se transmite al mempool. Tiene 0 confirmaciones. +La transacción 2 está incluida en el próximo anclaje de bloque. Tiene 1 confirmación. +El próximo bloque de Stacks confirma el bloque anterior. La transacción 2 tiene 2 confirmaciones. +El próximo bloque de Stacks confirma el bloque anterior. La transacción 2 tiene 3 confirmaciones. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Habilitar microbloques + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transacciones + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Minería + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Desarrollando con microbloques + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Buenas prácticas + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Manejo de nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Diseño de aplicación + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Exploradores + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Billeteras + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Aplicaciones + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..2764c660dd --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Minería +description: Una guía para la minería en Stacks 2.0 +sidebar_position: 4 +--- + +## Introducción + +Esta guía destaca algunos detalles técnicos relacionados con la minería en la red Stacks 2.0. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Frecuencia de minería + +Un nuevo bloque de Stacks puede ser minado una vez por bloque de Bitcoin. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Los mineros reciben recompensas de monedas por los bloques que ganen. + +Los montos de recompensa son: + +- 1000 STX por bloque son liberados en los primeros 4 años de minería +- 500 STX por bloque son liberados durante los siguientes 4 años +- 250 STX por bloque son liberados durante los siguientes 4 años +- 125 STX por bloque son liberados desde entonces indefinidamente. + +Estos "halvings" se sincronizan con los halvings de Bitcoin. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Comisiones de las transacciones + +Los mineros reciben comisiones de Stacks por las transacciones extraídas en cualquier bloque que producen. + +Para las transacciones extraídas en microbloques, el minero que produce el microbloque recibe el 40% de las comisiones, mientras que el minero que confirma el microbloque recibe 60% de las comisiones. + +## Madurez de recompensa + +Las recompensas por bloque y las tarifas de transacción tardan 100 bloques en la blockchain de Bitcoin en madurar. Después de extraer con éxito un bloque, sus recompensas aparecen en su cuenta de Stacks después de ~ 24 horas. + +## Minería con proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +La minería PoX es una modificación de la minería Proof-of-Burn (PoB) en lugar de enviar el bitcoin entregado a una dirección de quemado, se transfiere a los poseedores elegibles de STX que participan en el protocolo de Stacking. + +:::note +Un minero de PoX solo puede recibir tokens STX recién mintados cuando transfieren bitcoins a los dueños elegibles de tokens STX +::: + +![Mining flow](/img/pox-mining-flow.png) + +Los mineros ejecutan los nodos de Stacks con minería habilitada para participar en el mecanismo PoX. El nodo implementa el mecanismo PoX, que garantiza un manejo adecuado e incentivos a través de cuatro fases clave: + +- Registro: los mineros se registran para una futura elección enviando datos de consenso a la red +- Compromiso: los mineros registrados transfieren Bitcoin para participar en la elección. Los BTC comprometidos se envían a un conjunto titulares de tokens STX participantes +- Elección: una función aleatoria verificable elige un minero para escribir un nuevo bloque en la blockchain de Stacks +- Ensamblado: el minero elegido escribe el nuevo bloque y recolecta recompensas en forma de nuevos tokens STX + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microbloques + +La blockchain de Stacks produce bloques al mismo ritmo que la cadena de bloques de Bitcoin. Para proporcionar transacciones de menor latencia, los mineros pueden optar por habilitar microbloques. Los microbloques permiten al líder del bloque actual transmitir transacciones e incluir sus estais de transiciones en el epoch actual. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +El modelo de la trasmisión de bloques se describe en [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..1e24195cb1 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,146 @@ +--- +title: Red +description: Guía de la red Stacks 2.0 +sidebar_position: 5 +--- + +## Tokens + +Los tokens de Stacks (STX) son los tokens nativos en la blockchain Stacks 2.0. La fracción más pequeña es un micro-STX. 1,000,000 micro-STX hacen un Stack (STX). + +Los montos de STX deben almacenarse como enteros (8 bytes de longitud), y representados en montos de micro-STX. Para propósitos de visualización, el micro-STX se divide entre 1,000,00 (precisión decimal de 6). + +## Comisiones + +Las comisiones se utilizan para compensar a los mineros por confirmar las transacciones en la blockchain Stacks 2.0. La comisión se calcula en base a la tasa estimada de comisión y al tamaño de la transacción en peso bruto en bytes. La tasa de comisión es una variable determinada por el mercado. Para la [testnet](testnet)se establece en 1 micro-STX. + +Las estimaciones de comisiones pueden obtenerse a través del endpoint [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer): + +```bash +# para mainnet, reemplazar `testnet` por `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +La API responderá con la tasa de comisión (como entero): + +```json +1 +``` + +[La librería Stacks JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) soporta estimación de comisiones para: + +- transferencias de token (`estimateTransfer`) +- publicación de contrato (`estimateContractDeploy`) +- llamadas a contrato sin solo-lectura (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Cada cuenta lleva una [propiedad nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) que indica el número de transacciones procesadas para la cuenta dada. Las nonces son códigos de un solo uso, comenzando en `0` para cuentas nuevas e incrementado en 1 en cada transacción. + +Los onces se añaden a todas las transacciones y ayudan a identificarlas con el fin de asegurar que las transacciones se procesan en orden y para evitar un proceso duplicado. + +:::tip +El mecanismo de consenso también asegura que las transacciones no sean "repetidas" de dos maneras. En primer lugar, los nodos consultan las transacciones no gastadas (UTXOs) en orden de satisfacer sus condiciones de gasto en una nueva transacción. En segundo lugar, mensajes son enviados entre nodos para revisar la secuencia de números. +::: + +Cuando se construye una nueva transacción de transferencia de tokens, se debe obtener y establecer el nonce más reciente de la cuenta. + +:::tip La API proporciona un endpoint para [simplificar el manejo de nonce](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmaciones + +La red Stacks 2.0 está anclada a la red bitcoin. Esto permite que las transacciones en Stacks hereden la misma finalidad y seguridad de la blockchain de Bitcoin. + +El tiempo para minar un bloque, para confirmar las transacciones, eventualmente coincidirá con el "tiempo de bloque" esperado de la red bitcoin: 10 minutos. + +:::tip Las transacciones también se pueden ser minadas en [microbloques](microblocks), reduciendo la latencia significativamente. ::: + +El tiempo del bloque está codificado y cambiará a lo largo de las fases de implementación de la [red de pruebas](testnet). El tiempo actual del bloque se puede obtener a través del endpoint [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times): + +```bash +# para mainnet, reemplazar `testnet` por `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +La API responderá con el tiempo del bloque (en segundos): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Llamadas a funciones de solo-lectura + +Los contratos inteligentes pueden exponer las llamadas a funciones públicas. Para las funciones que hacen modificaciones de estado a la blockchain, las transacciones deben ser generadas y transmitidas. + +Sin embargo, para llamadas de solo-lectura, las transacciones **no son** requeridas. En su lugar, estas llamadas se pueden hacer utilizando la [API de Stacks Blockchain](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::caution Llamadas de contratos solo-lectura no requieren transacciones::: + +Se puede hacer una llamada de solo-lectura utilizando el endpoint [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function): + +```bash +# para mainnet, reemplazar `testnet` por `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks. o/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender":.", + "arguments": [, +}' +``` + +Ejemplo de respuesta para una llamada exitosa: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. La librería [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) soporta estas operaciones ::: + +## Consultas + +Los detalles de la red de Stacks 2.0 pueden ser consultados usando la [API de Stacks Blockchain](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Comprobación de estado + +El [comprobador de estado](https://stacks-status.com/) es un servicio que proporciona una interfaz de usuario para revisar rápidamente la salud de la blockchain de Stacks 2.0. + +### Información de la red + +La información de la red se puede obtener usando el endpoint [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info): + +```bash +# para mainnet, reemplazar `testnet` por `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Ejemplo de respuesta: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..30d5c8a6df --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Prueba de transferencia +description: Conozca el mecanismo de consenso de prueba de transferencia +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Los algoritmos de consenso para los *blockchains* requieren recursos computacionales o financieros para lograr que el *blockchain* sea seguro. La práctica general del consenso descentralizado consiste en lograr que sea prácticamente inviable que cualquier actor malicioso tenga suficiente poder computacional o participación en la propiedad para atacar la red. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![Mecanismo de PoX](/img/pox-mechanism.png) + +Esto permite que los participantes de dicha red aseguren la red de la criptomoneda y ganen una recompensa en la criptomoneda base. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks utiliza [Bitcoin](#why-bitcoin) como su cadena de anclaje. + +![Participantes de la PoX](/img/pox-participants.png) + +## ¿Por qué Bitcoin? + +Hay una serie de razones por las que Stacks eligió a Bitcoin como el *blockchain* para generar consenso. Es el protocolo de *blockchain* más antiguo, lanzado en 2009, y se ha convertido en un activo reconocido fuera de la comunidad relacionada con las criptomonedas. BTC ha contado con una mayor capitalización en el mercado en comparación con cualquier otra criptomoneda durante la última década. + +Bitcoin defiende la simplicidad y la estabilidad, y ha superado la prueba del tiempo. Influir o atacar la red es inviable o poco práctico para cualquier posible *hacker*. Es una de las pocas criptomonedas que captan la atención pública. Bitcoin es un nombre popular y es reconocido como un activo por gobiernos, grandes corporaciones e instituciones bancarias tradicionales. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +El SIP-001 proporciona una lista completa [de las razones por las que Bitcoin fue elegido para asegurar Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Bloques y microbloques + +El *blockchain* de Stacks permite aumentar el rendimiento de las transacciones mediante un mecanismo denominado microbloques. Bitcoin y Stacks progresan al mismo tiempo, y sus bloques se confirman simultáneamente. En Stacks, esto se denomina «bloque de anclaje». Un bloque de transacciones de Stacks completo corresponde a una sola transacción en Bitcoin. Esto mejora significativamente la relación coste/byte para el procesamiento de las transacciones en Stacks. Debido a la creación simultánea de bloques, Bitcoin limita la velocidad con la que se crean los bloques en Stacks, evitando así ataques de denegación de servicio a dicha red. + +Sin embargo, entre los bloques de anclaje de Stacks que se asientan en *blockchain* Bitcoin, también hay un número variable de microbloques que permiten asentar rápidamente las transacciones de Stacks con un alto grado de confianza. Esto logra que el rendimiento de las transacciones de Stacks escale independientemente de Bitcoin, al mismo tiempo que las mismas se asienten periódicamente, pero de forma definitiva, en la cadena Bitcoin. El *blockchain* Stacks adopta un modelo de flujo de bloques en el que cada líder puede seleccionar y agrupar, de forma adaptativa, las transacciones en su bloque a medida que llegan al mempool. Por lo tanto, cuando se confirma un bloque de anclaje, se agrupan y procesan todas las transacciones en el flujo principal del microbloque. Este es un método sin precedentes que permite lograr escalabilidad sin crear un protocolo totalmente separado de Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Desbloquear el capital de Bitcoin + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Desbloquear Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..180ca9b909 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introducción al mecanismo de recompensa de la prueba de transferencia +sidebar_position: 11 +--- + +## Introducción + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking es una acción integrada, requerida por el mecanismo de "proof-of-transfer" (PoX). The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Flujo del Stacking + +El mecanismo de Stacking puede presentarse como un flujo de acciones: + +![Flujo del Stacking](/img/stacking-illustration.png) + +1. Realizar llamadas API para obtener detalles sobre el próximo ciclo de recompensas +2. Para una cuenta de Stacks específica, confirmar elegibilidad +3. Confirmar la dirección de recompensa de BTC y la duración del bloqueo +4. La transacción se transmite y los tokens STX se bloquean. Esto debe suceder antes de la fase de preparación del próximo ciclo de recompensas, los últimos 100 bloques de Bitcoin de la fase de recompensas en curso +5. El mecanismo de Staking ejecuta ciclos de recompensa y envía recompensas a la dirección de recompensa BTC establecida +6. Durante el período de bloqueo, se pueden obtener detalles sobre el tiempo de desbloqueo, recompensas y más +7. Una vez que pasa el período de bloqueo, los tokens son liberados y accesibles de nuevo +8. Muestra el historial de recompensas, incluyendo detalles como ganancias de ciclos de recompensa anteriores + +:::info Ten en cuenta que la duración de un ciclo de recompensa es de ~2 semanas. Esta duración se basa en el tiempo de bloque objetivo de la red (10 minutos) y puede ser mayor a veces debido a [variaciones de tiempo de confirmación](https://www.blockchain.com/charts/median-confirmation-time) de la red bitcoin. ::: + +## Flujo de delegación Staking + +El flujo de Staking es diferente para los casos de uso de la delegación: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Antes de que se pueda iniciar el Stacking para un poseedor de tokens, el delegador necesita que se le conceda permiso en nombre del propietario de la cuenta. El permiso está restringido a la cantidad máxima que el delegado puede delegar. La cantidad máxima no está limitada por los fondos disponibles y puede establecerse mucho más alta. Una cuenta sólo puede ser asociada con un solo delegador +- La cuenta tiene que definir la relación de delegación. Opcionalmente pueden restringir la dirección de recompensa de Bitcoin que debe ser utilizada para los pagos, y la altura del bloque de caducidad para el permiso, limitando así el tiempo que un delegador tiene permiso para delegar +- Los Delegadores deben bloquear Stacks de diferentes cuentas ("fase de pool") hasta que alcancen la cantidad mínima de Stacks requeridos para participar en Stacking +- Una vez que un delegador bloquea suficientes tokens STX, pueden finalizar y comprometer su participación en el próximo ciclo de recompensas +- Ciertas relaciones de delegación pueden permitir al titular de STX recibir el pago directamente del minero (paso 5/6) +- La terminación de la relación con la delegación puede ocurrir automáticamente según las reglas de vencimiento establecidas o mediante la revocación activa de los derechos de delegación + +## Elegibilidad del poseedor del token + +Los poseedores de tokens Stacks (STX) no reciben automáticamente recompensas de Stacking. En su lugar, deben hacer: + +- Comprometerse a participar antes de que comience un ciclo de recompensas +- Compromete la cantidad mínima de tokens STX para asegurar un slot de recompensas, o agrupe con otros para alcanzar el mínimo +- Bloquear tokens STX para un período específico +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +El siguiente diagrama describe cómo se determinan los tokens mínimos de STX por slot. Más información sobre [mínimos dinámicos para stacking](https://stacking.club) está disponible en stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Los poseedores de token tienen una variedad de proveedores y herramientas para apoyar su participación en Stacking. El sitio web de Stacks contiene una [lista de proveedores de stacking y pools](https://stacks.org/stacking#earn). + +## Staking en el algoritmo de consenso de PoX + +El Stacking es una capacidad integrada de PoX y se produce a través de un conjunto de acciones en la blockchain de Stacks. Los [detalles completos de la implementación de proof-of-transfer](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) están en SIP-007. A continuación se muestra un resumen de las acciones más relevantes del algoritmo. + +![PoX cycles](/img/pox-cycles.png) + +- El Stacking ocurre sobre ciclos de recompensa con una duración fija. En cada ciclo de recompensa, un conjunto de direcciones de Bitcoin asociadas con los participantes de staking reciben recompensas BTC +- Un ciclo de recompensa consta de dos fases: preparar y recompensar +- Durante la fase de preparación, los mineros deciden un bloque de anclaje y un conjunto de recompensas. Minar cualquier bifurcación descendiente del bloque ancla requiere transferir fondos de minería a las direcciones de recompensa apropiadas. El conjunto de recompensas es el conjunto de direcciones de Bitcoin que son elegibles para recibir fondos en el ciclo de recompensa +- Los mineros se registran como candidatos líderes para una futura elección enviando una transacción clave que quema criptomoneda. La transacción también registra la sugerencia de cadena preferida del líder (debe ser un descendiente del bloque ancla) y los fondos comprometidos a 2 direcciones del conjunto de recompensas +- Los poseedores de token se registran para el próximo ciclo de recompensas mediante la transmición un mensaje firmado que bloquea los tokens STX asociados durante un período de bloqueo especificado en el protocolo, especifica una dirección de Bitcoin para recibir los fondos, y vota en el tip de la cadena de Stacks +- Múltiples líderes pueden comprometerse con la misma tip de la cadena. El líder que gana la elección y los compañeros que también queman por ese líder comparten colectivamente la recompensa, proporcional a cuánto se quemó cada uno +- Los tokens bloqueadas de los tenedores de tokens se desbloquean automáticamente tan pronto como finaliza el período de bloqueo + +## Dirección de Bitcoin + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +El contrato de stacking necesita un formato especial para la dirección de Bitcoin (la dirección de recompensa). Esto es necesario para asegurar que los mineros puedan construir correctamente la transacción de Bitcoin que contiene la dirección de recompensa. + +La dirección debe especificarse en el siguiente formato utilizando el lenguaje de Clarity: + +```clar +;; una tupla de una versión y buffer de hashbytes +(pox-addr (tuple (versión (buff 1)) (hashbytes (buff 20)))) +``` + +La `versión` del búfer debe representar qué tipo de dirección de bitcoin está siendo enviada. Puede ser uno de los siguientes: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), igual que p2pkh de bitcoin +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), al igual que el multisig p2sh de bitcoin, +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), igual que el p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), igual que el p2sh-p2wsh de bitcoin +``` + +Los `hashbytes` son los 20 hash bytes de la dirección bitcoin. Puedes obtenerlo de una librería de bitcoin, por ejemplo usando [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Elegir la estrategia de Stacking adecuada + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +Puedes acumular solo, en un pool o en un exchange: + +### Staking por tu cuenta + +Staking por su cuenta no es custodial. + +Staking por su cuenta requiere un mínimo de protocolo (cantidad cambia pero alrededor de 100.000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) permite hacer staking por tu cuenta. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Algunos pools disponibles son: + +| Pool | Tipo | Pays rewards in | Fee | Cantidad mínima | +| --------------------------------------------------- | ------------- |:---------------:| --- |:---------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Hacer Staking en un exchange + +Hacer Stacking en un exchange es custodial, lo que significa que confías tus Stacks al exchange. + +Varios exchanges permiten hacer stacking directamente en sus sitios. Ejemplos son [Okcoin](https://www.okcoin.com) y [Binance](https://www.binance.com/en/staking) + +## Estadísticas de stacking + +Puedes ver todo tipo de datos de stacking y estadísticas en [Stacking Club](https://stacking.club) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..1da394f495 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introducción +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..b589123173 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Especificaciones técnicas +description: Resumen de las especificaciones técnicas de Stacks 2.0 +sidebar_position: 13 +--- + +## Consenso + +- Prueba de Transferencia (PoX) como se describe en [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- La red pasará a la Prueba de Burn (PoB) como se describe en [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) después de 10 años. [Más información sobre Proof-of-Burn en SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Modelo de amenaza + - El 51% del poder de minería maliciosa en Stacks puede realizar un ataque de doble gasto + - El 51% del poder de minería maliciosa de Bitcoin puede reorganizar la cadena de Stacks +- Diferentes actores y sus funciones + - Los mineros de Stacks empaquetan transacciones en bloques, las minan a través de una transacción de Bitcoin, las propagan y, si ganan la carrera de bloques, agregan microbloques a su bloque ganador hasta que se mina el siguiente bloque. El siguiente bloque confirma el flujo de microbloques. + - Los holders de Stacks pueden alterar el cálculo de los límites de bloque (sujeto al veto de los mineros) y pueden votar para dashabilitar las recompensas de prueba de transferencia por un ciclo de recompensa. +- Las transacciones se consideran definitivas cuando finaliza la correspondiente transacción de "commit de bloque" en Bitcoin. Normalmente esto puede ser por 3-6 confirmaciones. +- Para obtener más información, consulte [Prueba de Transferencia](proof-of-transfer). + +## Minería en Prueba de transferencia + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Cuentas y direcciones + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transacciones + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## Vea también + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..9e2db6a8dd --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Prueba tus contratos inteligentes y aplicaciones +sidebar_position: 12 +--- + +## Acerca de Testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. Es una red utilizada por los desarrolladores para probar sus aplicaciones, contratos inteligentes o cambios en el protocolo en un entorno similar al de producción. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..5ebb5402b6 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transacciones +description: Guía de transacciones Stacks 2.0 +sidebar_position: 9 +--- + +## Introducción + +Las transacciones son la unidad fundamental de la ejecución en el blockchain de Stacks. Cada transacción se origina a partir de una [Cuenta Stacks 2.0](accounts), y se mantiene en el historial de la blockchain de Stacks para la eternidad. Esta guía te ayuda a entender las transacciones de Stacks 2.0. + +## Ciclo de vida + +Las transacciones pasan por fases antes de ser finalmente confirmadas, y disponibles para todos, en la red Stacks 2.0. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generar**: Las transacciones se ensamblan según la especificación de la codificación. +- **Validar y firmar**: Las transacciones son validadas para confirmar que están bien formadas. Las firmas requeridas son llenadas. +- **Broadcast**: Las transacciones son enviadas a un nodo. +- **Registrar**: Un minero recibe transacciones, verifica y las agrega al ["mempool,"](https://academy.binance.com/en/glossary/mempool) un área de retención para todas las transacciones pendientes. +- **Procesar**: Los mineros revisan el mempool y seleccionan las transacciones para el siguiente bloque a ser extraído. Dependiendo del tipo de transacción, pueden ocurrir diferentes acciones durante este paso. Por ejemplo, se podrían verificar las condiciones posteriores para una transferencia de tokens, se podrían acuñar tokens definidos por contrato inteligente, o se podría intentar llamar a un método de contrato inteligente existente. +- **Confirma**: Los mineros minan con éxito bloques con un conjunto de transacciones. Las transacciones dentro de la red se propagan con éxito. + +:::note Una transacción puede tener uno de tres estados una vez registrado: `pending`, `success`, o `failed`. ::: + +## Tipos + +Stacks 2.0 soporta un conjunto de diferentes tipos de transacción: + +| **Tipo** | **Valor** | **Descripción** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | La primera transacción en un nuevo bloque (una entidad que contiene varias transacciones). Utilizado para registrar las recompensas del bloque. No se generan y transmiten de forma manual como otros tipos de transacciones. | +| Token transfer | `token_transfer` | Transferencia de asset de un remitente a un destinatario | +| Contract deploy | `smart_contract` | Instanciación del contrato | +| Contract call | `contract_call` | Llamada de contrato para una función pública que no sea de solo-lectura | +| Poison Microblock | `poison_microblock` | Castigar a los líderes que intencionalmente empaquetan microbloques equívocos | + +Un ejemplo de cada tipo de transacción se puede encontrar en la [definición de respuesta de la API Stacks Blockchain para transacciones](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Llamadas de contratos solo-lectura **no** requieren transacciones. Lea más al respecto en la guía de red [](network#read-only-function-calls). ::: diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..2b5d805070 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Prueba de transferencia](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..4f8b39fb4d --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Tutoriales de la comunidad +description: Tutoriales creados por diversas personas de la comunidad de Stacks +--- + +Estos tutoriales han sido creados por varios miembros de la comunidad de Stacks. ¿Tienes un tutorial para sugerir? Ver la [guía de contribución](http://localhost:3000/docs/contribute/docs) para enviar un PR con un nuevo tutorial añadido. + +## Tutoriales Escritos + +- [Crear una aplicación de Stacks renderizada en el servidor con Remix](https://micro-stacks.dev/guides/with-remix) +- [Construir una aplicación de Stacks con Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creación de un contrato de voto](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Construir un NFT con Stacks y Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Acuñar NFTs con QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..017f559a5c --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Universo de Clarity + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Tutoriales de la comunidad + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..84f6723c16 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Pre requisitos + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/es/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index d4e4fb8259..5573920f9e 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## Acerca de Testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. Es una red utilizada por los desarrolladores para probar sus aplicaciones, contratos inteligentes o cambios en el protocolo en un entorno similar al de producción. Produce bloques aproximadamente a la misma velocidad que en mainnet; alrededor de 1 bloque cada 10 minutos en promedio. La red testnet de Stacks rara vez se reinicia. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. Es una red utilizada por los desarrolladores para probar sus aplicaciones, contratos inteligentes o cambios en el protocolo en un entorno similar al de producción. Produce bloques aproximadamente a la misma velocidad que en mainnet; alrededor de 1 bloque cada 10 minutos en promedio. La red testnet de Stacks rara vez se reinicia. ### Faucet @@ -30,4 +30,4 @@ La API Stacks Blockchain para la red de pruebas testnet está disponible en esta https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/es/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index 8fb14ca8f2..ff52036e70 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### salida: `int | uint` #### firma: `(pow i1 i2)` #### descripción: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### ejemplo: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `func` argument must be a literal function name. Applicable sequence types a ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(map func sequence_A sequence_B ... sequence_N)` #### descripción: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### descripción: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### ejemplo: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1384,4 +1389,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..0325c1ac40 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2031 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Importantly, the supplied arguments are evaluated in-order and lazily. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +Also, note that, no matter what kind of sequences the inputs are, the output is always a list. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `func` argument must be a literal function name. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +This hash uniquely identifies Stacks blocks and is unique across Stacks forks. Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. The `time` property returns an integer value of the block header time field. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/fr/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..b2fef628f9 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/fr/docusaurus-plugin-content-docs/current/contribute/translations.md index bd9a452333..fe8f8c6027 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..086aadd794 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Envoi de Bitcoin avec le portefeuille Hiro](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..260dd4184b --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Envoi de Bitcoin avec le portefeuille Hiro +description: Lancer une transaction standard Bitcoin avec le portefeuille Hiro +--- + +En utilisant le portefeuille web d'Hiro, nous pouvons facilement initier une transaction Bitcoin simple avec seulement quelques lignes de code. + +Vous devrez être authentifié avec le portefeuille Hiro pour que cela fonctionne, consultez comment faire dans le guide [Authentification avec Stacks.js](./stacks-js-auth). + +Une fois que vous avez connecté le portefeuille, vous pouvez utiliser l'API Hiro Wallet pour initier une simple transaction Bitcoin dans votre application JS de cette façon. + +```javascript +const sendBitcoin = async () => { + const resp = attendre window.btc?. equest("sendTransfer", { + adresse: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //remplacez ceci par n'importe quelle adresse que vous voulez envoyer au montant de + : "10000", // le montant que vous voulez envoyer en satoshis + }); + + // Stockage de txid dans le stockage local + // Nous récupérerons la transaction IF, que nous pouvons ensuite utiliser pour faire ce que nous voulons + si (typeof window ! = "undefined") { + localStorage. etItem("txid", JSON.stringify(resp.resultat. xid)); + } + + // Nous pouvons vouloir faire quelque chose une fois cette transaction confirmée, pour que nous puissions le mettre en attente ici et ensuite utiliser une API comme mempool. le rythme de requête de la chaîne Bitcoin pour obtenir des informations sur cette transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Ensuite, tout ce que nous ferions est de brancher notre bouton pour appeler cette fonction `sendBitcoins`. + +```javascript + +``` + +Vous pouvez jeter un coup d'œil au guide [Vérifier une transaction sur la chaîne BTC](./verifying-a-btc-tx-was-mined.md) pour voir un flux utilisateur plus complexe de vérification d'une transaction qui a été miné en utilisant cet ID retourné comme point de départ. + +Vous pouvez jeter un coup d'oeil à un peu plus d'informations sur cette simple API sur la [documentation du développeur de portefeuille Hiro](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/fr/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2067e7d57c..3f58ca5e68 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/fr/docusaurus-plugin-content-docs/current/gaia/gaia.md index 1070857350..f86a0d61dc 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/fr/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/intro.md b/i18n/fr/docusaurus-plugin-content-docs/current/intro.md index 7d38997514..f284f060c8 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Introduction a la Documentation de Stacks +# Stacks Docs -Bienvenue à la documentation officielle de Stacks, apportée par la communautée. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Découvre le minage de Stacks, le jeton STX et le language de programmes Clarity. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..15df918d04 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 305ad0b5ca..5afd34c23f 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Une fois terminé, il ne reste plus que quelques étapes pour faire fonctionner un mineur Proof-of-Burn sur le réseau principal. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Finally, start bitcoind as follows: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. +Next, update the bitcoin configuration: -## Exécution d'un mineur - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Mettez à jour les propriétés suivantes : +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Running a miner in Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Prerequisites +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Generate keychain and get mainnet tokens in Windows +### Generate a keychain -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Mettez à jour les propriétés suivantes : +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Mettez à jour les propriétés suivantes : +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -313,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index fbc4c25f00..c0a27e63d5 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Exécution d'un mineur - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Mettez à jour les propriétés suivantes : - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Mettez à jour les propriétés suivantes : +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Mettez à jour les propriétés suivantes : +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -324,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 89af343dc6..cd216e7103 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/glossary.md index f97908371a..3ea755ab54 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blochain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). More information and example [here](../services-using-stacks/wallets). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..55d0165def --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..eb5f68eaa4 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Inscription et se connection des utilisateurs avec des identités sur la blockchain de Stacks +sidebar_position: 8 +--- + +## Introduction + +Ce guide explique comment l'authentification est effectuée sur la blockchain de Stacks. + +L'authentification permet aux utilisateurs de s'identifier à une application tout en conservant un contrôle total sur leurs identifiants et leurs informations personnelles. Elle peut être intégré seul ou utilisé en conjonction avec [la signature de transactions](https://docs.hiro.so/get-started/transactions#signature-and-verification) et [le stockage de données](https://docs.stacks.co/gaia/overview), pour lesquels il s'agit d'un prérequis. + +Les utilisateurs qui s'inscrivent à votre application peuvent ensuite s'authentifier à n'importe quelle autre application avec le support du [Blockchain Naming System](bns) et vice versa. + +## Comment ça fonctionne + +Le flux d'authentification avec Stacks est similaire au flux typique client-server utilisé par les services de connexion centralisée (par exemple, OAuth). Cependant, avec les stacks, le flux d'authentification est produit entièrement côté client. + +Une application et un authentificateur tels que [le Portefeuille Stacks](https://www.hiro.so/wallet/install-web), communiquent pendant le flux d'authentification en transmettant deux jetons. L'application initiatrice envoie à l'authentificateur un jeton `authRequest`. Une fois qu'un utilisateur approuve l'authentification, l'authentificateur répond à l'application avec un jeton `authResponse`. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. Ils sont passés via des requêtes d'URL. + +Lorsqu'un utilisateur choisit d'authentifier une application, il envoie le jeton `authRequest` à l'authentificateur via une requête URL avec un paramètre également nommé : + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +Lorsque l'authentificateur reçoit la requête, il génère un jeton `authResponse` pour l'application en utilisant une _clé de transit éphémère_. La clé de transit éphémère est juste utilisée pour l'instance particulière de l'application, dans ce cas, pour signer la `authRequest`. + +L'application stocke la clé de transit éphémère lors de la génération de la requête. La partie publique de la clé de transit est passée dans le jeton `authRequest`. L'authentificateur utilise la partie publique de la clé pour chiffrer une _clé privée de l'application_ qui est retournée via la `authResponse`. + +L'authentificateur génère la clé privée de l'application à partir de la _adresse privée de l'utilisateur_ et du domaine de l'application. La clé privée de l'application est utilisée pour trois fonctions : + +1. Elle est utilisés pour créer des informations d'identification qui permettent à l'application d'accéder à un seau de stockage (stockage temporaire) dans le hub Gaia de l'utilisateur +2. Il est utilisé pour le chiffrement de bout en bout des fichiers stockés pour l'application dans le stockage Gaia de l'utilisateur. +3. Il sert de secret cryptographique que les applications peuvent utiliser pour exécuter d'autres fonctions cryptographiques. + +Enfin, la clé privée de l'application est déterministe, ce qui signifie que la même clé privée sera toujours générée pour une adresse et un domaine donnés de Stacks. + +Les deux premières de ces fonctions sont particulièrement pertinentes pour le stockage de données [avec Stacks.js](https://docs.stacks.co/docs/gaia). + +## Paire de clés + +L'authentification avec Stacks utilise largement la cryptographie à clé publique en général et ECDSA avec la courbe `secp256k1` en particulier. + +Les sections suivantes décrivent les trois paires de clés publiques privées, y compris la façon dont elles sont générées, où elles sont utilisées et à qui les clés privées sont divulguées. + +### Clé privée de transit + +La clé de transit privé est une clé éphémère utilisée pour chiffrer les secrets qui doivent passer de l'authentificateur à l'application pendant le processus d'authentification . Elle est générée aléatoirement par l'application au début de la réponse d'authentification. + +La clé publique, qui correspond à la clé privée de transit, est stockée dans un simle élément "tableau" dans la clé `public_keys` du jeton de requête d'authentification. L'authentificateur crypte les données secrètes telles que la clé privée de l'application en utilisant cette clé publique et la renvoie à l'application lorsque l'utilisateur se connecte à l'application. La clé privée de transit signe la demande d'authentification de l'application. + +### Clé privée de l'adresse d'identité + +La clé privée de l'adresse d'identité est dérivée de la phrase porte-clés de l'utilisateur et est la clé privée du nom d'utilisateur dans Stacks que l'utilisateur choisit d'utiliser pour se connecter à l'application. C'est un secret qui appartient à l'utilisateur et qui ne quitte jamais l'instance de l'authentificateur. + +Cette clé privée signe le jeton de réponse d'authentification pour une application pour indiquer que l'utilisateur approuve la connexion à cette application. + +### Clé privée de l'application + +La clé privée de l'application est une clé privée spécifique à l'application qui est générée à partir de la clé privée de l'adresse de l'utilisateur en utilisant le `domain_name` en entrée. + +La clé privée de l'application est partagée de manière sécurisée avec l'application pour chaque authentification, chiffrée par l'authentificateur avec la clé publique de transit. Parce que la clé de transit n'est stockée que sur le côté client, cela empêche une attaque de l'homme du milieu où un serveur ou un fournisseur Internet pourrait potentiellement détourner la clé privée de l'application. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..524b51e4fb --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,242 @@ +--- +title: Bitcoin Name System +description: Lier les noms d'utilisateur aux états hors chaîne +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +La blockchain de Stacks V1 a implémenté BNS à travers des opérations de noms de premier ordre (?). Dans les piles V2, le BNS a été remplacé par un contrat intelligent chargé durant le bloc genèse. + +Les noms dans BNS ont trois propriétés : + +- **Les noms sont globalement uniques.** Le protocole n'autorise pas les collisions de noms, et tous les noeuds de confiance résolvent un nom donné de la même façon. +- **Les noms sont en langage naturel.** Chaque nom est choisi par son créateur. +- **Les noms sont inaliénables.** Seul le propriétaire du nom peut changer l'état auquel il se réfère. Plus précisément, un nom est détenu par une ou plusieurs clés privées ECDSA. + +La blockchain Stacks assure que la vue BNS de chaque nœud est synchronisée avec tous les autres nœuds du monde, de sorte que les requêtes sur un nœud seront les mêmes sur les autres nœuds. Les nœuds de la blockchain Stacks permettent au propriétaire d'un nom de se lier jusqu'à 40 Ko d'état hors chaîne à leur nom, qui sera répliquée à tous les autres nœuds de blockchain de Stacks via un réseau P2P. + +La plus grande conséquence pour les développeurs est qu'en BNS, la lecture de l'état du nom est rapide et bon marché, mais l'écriture de l'état du nom est lente et coûteuse. C'est parce que l'enregistrement et la modification des noms nécessitent d'envoyer une ou plusieurs transactions à la blockchain sous-jacente, et les nœuds BNS ne les traiteront pas jusqu'à ce qu'ils soient suffisamment confirmés. Les utilisateurs et les développeurs ont besoin d'acquérir et de dépenser la cryptomonnaie requise (STX) pour envoyer des transactions BNS. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. Lorsque vous consultez un site Web, vous utilisez le Domain Name Service pour résoudre le nom d'hôte à l'adresse IP de son hôte. Lorsque vous consultez une branche Git, vous utilisez votre client Git pour résoudre le nom de la branche à un hachage de livraison. Lorsque vous regardez la clé PGP de quelqu'un sur un serveur de clés, vous résolvez son ID de clé à sa clé publique. + +Quelles sortes de choses voulons-nous être vraies en ce qui concerne les noms? En BNS, les noms sont globalement uniques, les noms ont un sens humain, et les noms sont inaliénables. Cependant, si vous regardez ces exemples, vous verrez que chacun d'eux garantit seulement _deux_ de ces propriétés. Cela limite leur utilité. + +- Dans le DNS et les médias sociaux, les noms sont globalement uniques et lisibles par l'homme, mais pas uniques. L'opérateur système a le dernier mot l'appartenance de chaque nom. + + - **Problème**: Les clients doivent faire confiance au système pour faire le bon choix dans ce qu'un nom donné signifie. Cela inclut la confiance que personne d'autre que les administrateurs système peuvent apporter ces modifications. + +- Dans Git, les noms de branches sont en langage humain et irrévocables, mais pas globalement uniques. Deux nœuds Git différents peuvent avoir le même nom de branche appartenant à différents dépôt non liés. + + - **Problème**: Puisque les noms peuvent faire référence à un état conflictuel, les développeurs doivent trouver un autre mécanisme pour résoudre les ambiguïtés. Dans le cas de Gitit , l'utilisateur doit intervenir manuellement. + +- En PGP, les noms sont des clés d'identification. They are globally unique and cryptographically owned, but not human-readable. Les identifiants de clés PGP sont dérivés des clés qu'ils référencent. + - **Problème**: Ces noms sont difficiles à retenir pour la plupart des utilisateurs puisqu'ils ne transmettent pas d'informations sémantiques relatives à leur utilisation dans le système. + +Les noms BNS ont les trois propriétés et aucun de ces problèmes. Cela en fait un outil puissant pour construire toutes sortes d'applications réseau. Avec BNS, nous pouvons faire ce qui suit et plus: + +- Construire des services de noms de domaine où les noms de domaine ne peuvent pas être détournés. +- Construire des plateformes de réseaux sociaux où les noms d'utilisateurs ne peuvent pas être volés par des hameçonneurs. +- Construire des systèmes de contrôle de version où les branches du dépôt ne sont pas en conflit. +- Construire une infrastructure à clé publique où il est facile pour les utilisateurs de découvrir et se souvenir des clés de chacun. + +## Organisation du BNS + +Les noms de BNS sont organisés en une hiérarchie globale de noms. Il y a trois couches différentes dans cette hiérarchie liée au nommage : + +- **Les espaces de nommage**. Ce sont les noms de premier niveau dans la hiérarchie. Une analogie avec les espaces de noms BNS sont des domaines de premier niveau DNS. Les espaces de noms BNS existants incluent `.id`, `.podcast`, et `.helloworld`. Tous les autres noms appartiennent à exactement un espace de noms. N'importe qui peut créer un espace de noms, mais afin que l'espace de noms soit maintenu, il doit être _launched_ pour que n'importe qui puisse y enregistrer des noms. Les espaces de nommage ne sont pas détenus par leurs créateurs. + +- **Les noms BNS**. Ce sont des noms dont les enregistrements sont stockés directement sur la blockchain . La propriété et l'état de ces noms sont contrôlés par l'envoi de transactions blockchain. Les exemples de noms incluent `verified.podcast` et `muneeb.id`. N'importe qui peut créer un nom BNS, à condition que l'espace de noms le contienne déjà. + +- **Les sous-domaines BNS**. Ce sont des noms dont les enregistrements sont stockés hors chaîne, mais sont ancrés collectivement dans la blockchain. La propriété et l'état de ces noms vivent dans les données du réseau P2P. Alors que les sous-domaines BNS sont détenus par des clés privées séparées, le propriétaire d'un nom BNS doit diffuser son état de sous-domaine. Les exemples de sous-domaines comprennent `jude.personal.id` et `podsaveamerica.verified.podcast`. Contrairement aux espaces de noms et noms BNS, l'état des sous-domaines BNS ne fait _pas_ partie des règles de consensus de la blockchain. + +Une matrice de comparaison de fonctionnalités résumant les similitudes et les différences entre ces objets de nom est présentée ci-dessous: + +| Fonctionalité | **Espaces de nommage** | **Noms BNS** | **Sous-domaines BNS** | +| ------------------------------------------------- | ---------------------- | ------------ | --------------------- | +| Globalement unique | X | X | X | +| Langage humain | X | X | X | +| Détenu par une clé privée | | X | X | +| Tout le monde peut créer | X | X | [1] | +| Le propriétaire peut mettre à jour | | X | [1] | +| État hébergé sur la chaîne | X | X | | +| Etat hébergé hors de la chaîne | | X | X | +| Comportement contrôlé par des règles de consensus | X | X | | +| Peut avoir une date d'expiration | | X | | + +[1] Nécessite la coopération d'un propriétaire du nom BNS pour diffuser ses transactions + +## Espaces de nommage + +Namespaces are the top-level name objects in BNS. + +Ils contrôlent quelques propriétés inhérentes aux noms : + +- Combien coûte leur enregistrement +- La durée avant de nécessiter leur renouvellement +- Qui (le cas échéant) reçoit les frais d'enregistrement du nom +- Qui est autorisé à initialiser l'espace de noms avec ses noms initiaux. + +Au moment de cette écriture, le plus grand espace de noms BNS est l'espace de noms `.id` . Les noms de l'espace de noms `.id` sont destinés à résoudre les identités de l'utilisateur . Les noms abrégés en `.id` sont plus chers que les noms longs, et doivent être renouvelés par leurs propriétaires tous les deux ans. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Contrairement aux DNS, _n'importe qui_ peut créer un espace de noms et définir ses propriétés. Les espaces de noms sont créés sur la base du premier arrivé, et une fois créés, ils durent pour toujours. + +Cependant, la création d'un espace de noms n'est pas libre. Le créateur d'espace de noms doit _brûler_ de la cryptomonnaie pour le faire. Plus l'espace de noms est court, plus la cryptomonnaie doit être brûlée (c'est-à-dire que les espaces de noms courts sont plus précieux que les espaces de noms longs). Par exemple, il a coûté à Blockstack PBC 40 BTC pour créer l'espace de noms `.id` en 2015 (dans la transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Les espaces de noms peuvent contenir entre 1 et 19 caractères, et sont composés des caractères `a-z`, `0-9`, `-`, et `_`. + +## Sous-domaines + +Les noms des BNS sont fortement détenus car le propriétaire de sa clé privée peut générer des transactions valides qui mettent à jour le hachage et le propriétaire de son fichier de zone. Cependant, cela demande d'obliger le propriétaire du nom à payer la transaction sous-jacente dans la blockchain de . De plus, cette approche limite le taux d'enregistrement des noms BNS et les opérations à la bande passante transactionnelle de la blockchain sous-jacente. + +BNS surmonte cela avec des sous-domaines. Un **sous-domaine BNS** est un type de nom BNS dont l'état et le propriétaire sont stockés en dehors de la blockchain, mais dont l'existence et l'historique des opérations sont ancrées dans la blockchain . Comme leurs homologues sur la chaîne, les sous-domaines sont globalement uniques, fortement possédés et en langage humain. BNS leur donne leur propre état de nom et clés publiques. Contrairement aux noms on-chain, les sous-domaines peuvent être créés et gérés à coût réduit, car ils sont diffusés sur le réseau BNS en lots. Une seule transaction blockchain peut envoyer jusqu'à 120 opérations de sous-domaine . + +Ceci est réalisé en stockant les enregistrements de sous-domaine dans les fichiers de zone de noms BNS. Un propriétaire de noms on-chain diffuse des opérations de sous-domaine en les encodant en tant qu'enregistrements `TXT` dans un fichier de zone DNS. Pour diffuser le fichier de zone, le nom propriétaire définit le hachage du nouveau fichier de zone avec une transaction `NAME_UPDATE` et réplique le fichier de zone. Ceci réplique, à son tour, toutes les opérations du sous-domaine qu'elle contient, et ancre l'ensemble des opérations de sous-domaine à une transaction sur la chaîne. Les règles de consensus du noeud BNS assurent que seules opérations de sous-domaine valides de __ `transactions NAME_UPDATE` valides ne seront jamais stockées. + +Par exemple, le nom `a été vérifié. odcast` une fois écrit le hachage du fichier de zone `247121450ca0e9af45e85a82e61cd525cd7ba023`, qui est le hachage du fichier de zone suivant : + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Chaque enregistrement `TXT` dans ce fichier de zone encode une création de sous-domaine. Par exemple, `1yeardaily.verified.podcast` se correspond à: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +Cette information a été extraite de l'enregistrement de la ressource `1yeardaily` `TXT` dans le fichier de zone pour `verified.podcast`. + +### Cycle de vie des sous-domaines + +Notez que `1yeardaily.verified.podcast` a une clé publique différente de `verified.podcast`. Un noeud BNS ne traitera une opération de sous-domaine ultérieure le `1yeardy. erified.podcast` que s'il contient une signature de la clé privée de cette adresse. `verified.podcast` ne peut pas générer mises à jour ; seul le propriétaire de `1yeardaily.verified.podcast`. peut le faire + +Le cycle de vie d'un sous-domaine et de ses opérations est affiché dans la figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2 : durée de vie du sous-domaine en ce qui concerne les opérations de noms on-chain . nouvelle +opération de sous-domaine ne sera acceptée que si elle a un numéro "séquence=" ultérieur, +et une signature valide en "sig=" sur le corps de la transaction. e champ "sig=" +inclut à la fois la clé publique et la signature, et la clé publique doit être hachée sur +le champ "addr=" de l'opération précédente de sous-domaine. + +Les transactions de création de sous-domaine et de transfert de sous-domaine pour +"cicero.res_publica.id" sont diffusées par le propriétaire de "res_publica.id". +Cependant, tout nom sur chaîne ("jude.id" dans ce cas) peut diffuser une mise à jour de sous-domaine +pour "cicero.res_publica.id". +``` + +Les opérations de sous-domaine sont ordonnées par numéro de séquence, à partir de 0. Chaque nouvelle opération de sous-domaine doit inclure : + +- Le numéro d'ordre suivant +- La clé publique qui hache à l'adresse de la précédente transaction de sous-domaine +- Une signature de la clé privée correspondante sur l'ensemble du sous-domaine opération. + +Si deux opérations de sous-domaine correctement signées mais conflictuelles sont découvertes (c.-à-d. ils ont le même numéro de séquence), celui qui se produit plus tôt dans l'histoire de la blockchain est accepté. Les opérations de sous-domaine non valides sont ignorées. + +Combiné, cela garantit qu'un noeud BNS avec tous les fichiers de zone avec les opérations d'un sous-domaine donné sera en mesure de déterminer la séquence valide de transitions d'état qu'il a soumises, et déterminez le fichier de zone actuel et le hachage de la clé publique pour le sous-domaine. + +### Création et gestion de sous-domaine + +Contrairement à un nom on-chaîne, un propriétaire de sous-domaine a besoin de l'aide du propriétaire de noms sur chaîne pour diffuser ses opérations de sous-domaine. En particulier : + +- Une transaction de création de sous-domaine ne peut être traitée que par le propriétaire du nom sur qui partage son suffixe. Par exemple, seul le propriétaire de `res_publica.id` peut diffuser des transactions de création de sous-domaine pour les noms de sous-domaine se terminant par `.res_publica.id`. +- Une transaction de transfert de sous-domaine ne peut être diffusée que par le propriétaire du nom sur la chaîne qui l'a créé. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. Cela permet au noeud BNS de prouver l'_absence<0> de tout conflit d'opération de création ou de transfert de sous-domaines lors de la création des nouveaux fichiers de zones.

+- Une transaction de mise à jour de sous-domaine peut être diffusée par _n'importe quel propriétaire de nom sur la chaîne,_ mais le propriétaire du sous-domaine doit trouver celui qui coopérera. Par exemple, le propriétaire de `verified.podcast` peut diffuser une transaction de mise à jour de sous-domaine créée par le propriétaire de `cicero.res_publica.id`. + +Cela dit, pour créer un sous-domaine, le propriétaire du sous-domaine génère une opération de création de sous-domaine pour le nom désiré et le donne au propriétaire du nom sur la chaîne. + +Une fois créé, un propriétaire de sous-domaine peut utiliser n'importe quel propriétaire de nom sur la chaîne pour diffuser une opération de mise à jour de sous-domaine. Pour ce faire, ils génèrent et signent l'opération de sous-domaine requise et la donnent à un propriétaire de nom sur la chaîne, qui l'empaquete alors avec d'autres opérations de sous-domaine dans un fichier de zone DNS et le diffuse sur le réseau. + +Si le sous-propriétaire du sous-domaine veut changer l'adresse de son sous-domaine, il a besoin de signer une opération de transfert de sous-domaine et la donner au propriétaire du nom sur chaîne qui a créé le sous-domaine. Ils l'empaquetent ensuite dans un fichier de zone et diffusent . + +### Enregistreurs de sous-domaine + +Parce que les noms de sous-domaine sont bon marché, les développeurs peuvent être enclins à exécuter des demandes d'enregistrement de sous-domaine pour le compte de leurs applications. Par exemple, le nom `personal.id` est utilisé pour enregistrer des noms d'utilisateur sans les obliger à faire une transaction Bitcoin. + +Nous fournissons une implémentation de référence d'un [Enregistrement BNS ](https://github.com/stacks-network/subdomain-registrar) pour aider les développeurs à diffuser des opérations de sous-domaine. Les utilisateurs posséderaient toujours leurs noms de sous-domaine; le bureau d’enregistrement donne simplement aux développeurs un moyen pratique de les enregistrer et de les gérer dans le contexte d’une application particulière. + +## BNS and DID Standards + +Les noms BNS sont conformes à la spécification de [de la Fondation d’identité décentralisée](http://identity.foundation) protocole pour les identifiants décentralisés (DID). + +Chaque nom dans BNS a un DID associé. Le format DID pour BNS est : + +```bash + did:stack:v0:{address}-{index} +``` + +Où : + +- `{address}` est un hachage de clé publique sur chaîne (par exemple une adresse Bitcoin). +- `{index}` fait référence au `nème` nom que cette adresse a créé. + +Par exemple, le DID pour `personal.id` est `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, parce que le nom `personal.id` a été le tout premier nom créé par `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +Comme autre exemple, le DID pour `jude.id` est `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Ici, l'adresse `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` avait créé un prénom plus tôt dans l'histoire avant celui-ci (qui se trouve être `abcdefgh123456. d`). + +Le but d'un DID est de fournir un identifiant éternel pour une clé publique. La clé publique peut changer, mais le DID ne changera pas. + +Stacks Blockchain implémente une méthode DID en elle-même afin d'être compatible avec d'autres systèmes qui utilisent DID pour la résolution de clé publique. Pour qu'un DID soit résolu, tout ce qui suit doit être vrai pour un nom : + +- Le nom doit exister +- Le hachage du fichier de zone du nom doit être le hachage d'un fichier de zone DNS bien formé +- Le fichier de zone DNS doit être présent dans les données du noeud Stacks. +- Le fichier de zone DNS doit contenir un enregistrement de la ressource `URI` qui pointe vers un jeton web JSON signé +- La clé publique qui a signé le jeton Web JSON (et qui est inclus avec celui-ci) doit être hachée à l'adresse qui est propriétaire du nom + +Tous les noms n'auront pas forcément de DIDs qui seront résolus pour les clés publiques. Cependant, les noms créés par l'outil standard auront les DIDs qui le font. + +Une API RESTful est en cours de développement. + +## DID Encoding for Subdomains + +Chaque nom et sous-domaine dans BNS a un DID. L'encodage est un peu différent pour les sous-domaines, donc le logiciel peut déterminer quel façon de coder choisir. + +- Pour les noms de BNS on-chain, le `{address}` est le même que l'adresse Bitcoin qui détient le nom. Actuellement, les adresses d'octets de version 0 et d'octets de version 5 sont prises en charge (c.-à-d. adresses commençant par `1` ou `3`, signifiant `p2pkh` et `p2sh` adresses). + +- Pour les sous-domaines BNS hors chaîne BNS, le `{address}` a un octet de version 63 pour sous-domaines appartenant à une seule clé privée, et l'octet de version 50 pour les sous-domaines appartenant à un ensemble m-of-n de clés privées. C'est-à-dire que les adresses DID de sous-domaine commencent par `S` ou `M`, respectivement. + +Le champ `{index}` pour un DID d'un sous-domaine est distinct du champ `{index}` pour le DID d'un BNS, même si la même chose crée des noms et des sous-domaines. Par exemple, le nom `abcdefgh123456. d` a le DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, parce que c'était le prénom créé par `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. Cependant, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _a aussi_ créé `jude.statism.id` comme premier nom de sous-domaine. Le DID pour `jude.statism.id` est `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Notez que l'adresse `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encode la même clé publique de hachage que l'adresse `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (la seule différence entre ces deux chaînes est que le premier est codé en base58check avec la version byte 0, et la seconde est encodée avec la version byte 63). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..9310aa65be --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..e6e93e130a --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..a0dc623d97 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,148 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a6f9b9ac96 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..938bdcd481 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: API de la blockchain Stacks +description: Interagir avec la Blockchain Stacks 2.0 via l'API +sidebar_position: 6 +--- + +## Introduction +L'API de la Blockchain Stacks 2.0 vous permet de interroger la blockchain Stacks 2.0 et d'interagir avec des contrats intelligents. Il a été construit pour maintenir des vues matérialisées paginables de la blockchain Stacks 2.0. + +:::tip API Documentation La documentation officielle de l'API est disponible [ici](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note Cette documentation ne couvre que les points de terminaison qui sont exposés sur un noeud Stacks, appelé l'API RPC. Pour une documentation complète sur l'API RESTful, consultez la [référence de l'API Hiro](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. Le chemin de base de l'API est : + +```bash +# pour mainnet, remplacez `testnet` par `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Points d'entrée du proxy Hiro pour de l'API RPC Stacks +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. Cependant, chaque nœud Stacks en cours d’exécution expose une API RPC, qui vous permet d’interagir avec la blockchain. Au lieu d'utiliser une API hébergée de manière centralisée, vous pouvez directement accéder à l'API RPC d'un noeud hébergé localement. + +Bien que le noeud API RPC ne donne pas les mêmes fonctionnalités que ceux de la Blockchain Stacks API 2.0 , vous obtenez des fonctionnalités similaires d'une manière qui est étendue à ce noeud spécifique. L'API RPC inclut les points d'entrée suivants : + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution Si vous exécutez un noeud local, il expose un serveur HTTP sur le port `20443`. Le point d'accès info serait `localhost:20443/v2/info`. ::: diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..ba6b18f0f7 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/fr/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 59934a5bde..ba6dee45a9 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/fr/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index a6011cca8b..c7708995b6 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `func` argument must be a literal function name. Applicable sequence types a ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1385,4 +1390,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the ```clarity (impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..32989bba8e --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2028 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `true`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. Also, note that, no matter what kind of sequences the inputs are, the output is always a list. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `concat` function takes two sequences of the same type, and returns a concatenated sequence of the same type, with the resulting sequence_len = sequence1_len + sequence2_len. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. This hash uniquely identifies Stacks blocks and is unique across Stacks forks. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +The `time` property returns an integer value of the block header time field. This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (map-get? names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (get-balance (account principal)) + (ok u0)) +(define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/hi/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..b2fef628f9 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/hi/docusaurus-plugin-content-docs/current/contribute/translations.md index bd9a452333..fe8f8c6027 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/hi/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2067e7d57c..3f58ca5e68 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/hi/docusaurus-plugin-content-docs/current/gaia/gaia.md index 1070857350..f86a0d61dc 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/hi/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/intro.md b/i18n/hi/docusaurus-plugin-content-docs/current/intro.md index 84f1eaa649..f284f060c8 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Docs Introduction +# Stacks Docs -Welcome to the community driven official Stacks Documentation. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Learn about Stacks mining, the STX token, and the Clarity smart contract language. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..15df918d04 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 468a01df66..5afd34c23f 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Finally, start bitcoind as follows: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. +Next, update the bitcoin configuration: -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Running a miner in Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Prerequisites +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Generate keychain and get mainnet tokens in Windows +### Generate a keychain -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Update the following properties: +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -313,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index b572df3ba2..c0a27e63d5 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command, and pass `-t` to indicate that we want a testnet keychain. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -324,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 89af343dc6..cd216e7103 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/hi/docusaurus-plugin-content-docs/current/references/glossary.md index 1027a52c96..20474763a7 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. More information and example [here](../services-using-stacks/wallets). Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..55d0165def --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..59a8929797 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Register and sign in users with identities on the Stacks blockchain +sidebar_position: 8 +--- + +## Introduction + +This guide explains how authentication is performed on the Stacks blockchain. + +Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/gaia/overview), for which it is a prerequisite. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## How it works + +The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..9f88fabff4 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,242 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." +``` + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Subdomain Creation and Management + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Each name in BNS has an associated DID. The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..9310aa65be --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..e6e93e130a --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..a0dc623d97 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,148 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a6f9b9ac96 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..ad9bb1822e --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introduction +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..ba6b18f0f7 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/hi/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/hi/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 59934a5bde..ba6dee45a9 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/hi/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/hi/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index 4605b2f4c9..10727f2566 100644 --- a/i18n/hi/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/hi/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `concat` function takes two sequences of the same type, and returns a concat ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1382,4 +1387,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..c664c233b0 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Ringkasan dan panduan untuk memulai Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity adalah bahasa kontrak pintar yang **dapat ditentukan** yang mengoptimalkan prediktabilitas dan keamanan, dirancang untuk blockchain Stacks. Kontrak pintar memungkinkan pengembang untuk mengkodekan logika bisnis penting di blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..318545408c --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2028 @@ +--- +title: Fungsi +description: Lihat daftar rinci semua fungsi untuk bahasa Clarity. +sidebar_position: 3 +tags: + - clarity +--- + +## Fungsi + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### deskripsi: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### contoh: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### deskripsi: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### contoh: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### deskripsi: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### contoh: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### deskripsi: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### contoh: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### deskripsi: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### contoh: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### deskripsi: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### contoh: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `true`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. Also, note that, no matter what kind of sequences the inputs are, the output is always a list. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `concat` function takes two sequences of the same type, and returns a concatenated sequence of the same type, with the resulting sequence_len = sequence1_len + sequence2_len. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. This hash uniquely identifies Stacks blocks and is unique across Stacks forks. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +The `time` property returns an integer value of the block header time field. This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (map-get? names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (get-balance (account principal)) + (ok u0)) +(define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..ca3a42eb57 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,147 @@ +--- +title: Kata kunci +description: Lihat daftar rinci semua kata kunci untuk bahasa Clarity. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Referensi kata kunci + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test + +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..b05ee33558 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Tipe +description: Lihat daftar rinci semua tipe untuk bahasa Clarity. +sidebar_position: 2 +tags: + - clarity +--- + +## Sistem Tipe Clarity + +Sistem tipe ini berisi: + +| Tipe | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..6b4389e015 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Kontrak Penting", + "position": 5, + "link": { + "type": "generated-index", + "description": "Kontrak Clarity yang telah diimplementasikan secara khusus yang pantas disebutkan." + } +} diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..c54d8727e4 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: Kontrak BNS +description: Sebuah Sistem Penamaan Bitcoin. +--- + +![](/img/satoshi-btc.png) + +## Pengantar + +BNS (Bitcoin Name System) dijalankan sebagai kontrak pintar menggunakan Clarity. + +Berikut adalah daftar fungsi publik dan hanya baca (read-only), serta kode kesalahan yang dapat dikembalikan oleh metode-metode tersebut: + +- [Fungsi yang dapat diakses publik](#public-functions) +- [Fungsi dengan akses baca saja](#read-only-functions) +- [Kode galat](#error-codes) + +## Fungsi yang dapat diakses publik + +### nama-impor + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Menyertakan nama ke dalam ruang nama yang terbuka. Setiap nama yang diimpor diberikan pemilik dan beberapa keadaan di luar rantai blok. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Memesan nama dengan memberitahukan seluruh node BNS hash yang diacak dari nama BNS. Biaya pendaftaran dibayarkan ke alamat yang telah ditetapkan oleh pemilik ruang nama. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Mengungkapkan salt dan nama ke semua node BNS, dan menetapkan hash kunci publik awal dan hash file zona untuk nama tersebut. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Fungsi dengan akses baca saja + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Kode galat + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..341ab34b1d --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Pengantar + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Berikut adalah daftar fungsi publik dan hanya baca (read-only), serta kode kesalahan yang dapat dikembalikan oleh metode-metode tersebut: + +- [Fungsi yang dapat diakses publik](#public-functions) +- [Fungsi dengan akses baca saja](#read-only-functions) +- [Kode galat](#error-codes) + +## Fungsi yang dapat diakses publik + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Fungsi dengan akses baca saja + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Kode galat + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..8e6ced96fb --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Pengantar + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/id/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/id/docusaurus-plugin-content-docs/current/contribute/docs.md index d177a03b4a..cc6a3747f0 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Terima kasih atas minat Anda yang ingin berkontribusi dan membantu membuat dokumen ini menjadi lebih baik. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/id/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/id/docusaurus-plugin-content-docs/current/contribute/translations.md index 04cc3c5f7c..98128b0d99 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Bantuan untuk terjemahan -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. Untuk membantu penerjemahan, buka [halaman ini](https://crowdin.com/project/docsstacksco), klik bahasa apa saja dan mulailah menerjemahkan. Semua bantuan akan dihargai. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..699f8a1dcc --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Token + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/id/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 1653a061ac..7e25e57bc7 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/id/docusaurus-plugin-content-docs/current/gaia/gaia.md index af9898274b..21d7ca8705 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Arsitektur penyimpanan terdesentralisasi untuk data luar-rantai -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Pengantar -Aplikasi yang dibuat dengan blockchain Stacks menyimpan data luar-rantai menggunakan sistem penyimpanan yang disebut Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Sementara metadata transaksional publik paling baik disimpan di blockchain Stacks, data aplikasi pengguna seringkali dapat disimpan lebih efisien dan pribadi di penyimpanan Gaia. @@ -38,7 +44,7 @@ Blockchain Stacks hanya menyimpan data identitas. Data yang dibuat oleh tindakan Hub Gaia berjalan sebagai layanan yang menulis ke penyimpanan data. Penyimpanan itu sendiri adalah penyimpanan nilai kunci sederhana. Layanan hub menulis ke penyimpanan data dengan meminta token autentikasi yang valid dari pemohon. Biasanya, layanan hub berjalan pada sumber daya komputasi dan penyimpanan itu sendiri pada sumber daya penyimpanan khusus yang terpisah. Biasanya, kedua sumber daya milik penyedia komputasi cloud yang sama. -![Penyimpanan Gaia](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Pendekatan Gaia terhadap desentralisasi berfokus pada kontrol pengguna atas data dan penyimpanannya. Pengguna dapat memilih penyedia hub Gaia. Jika pengguna dapat memilih penyedia hub Gaia mana yang akan digunakan, maka pilihan itu adalah semua desentralisasi yang diperlukan untuk mengaktifkan aplikasi yang dikontrol oleh pengguna. Selain itu, Gaia mendefinisikan API seragam untuk aplikasi untuk mengakses data tersebut. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/id/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/id/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/id/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/intro.md b/i18n/id/docusaurus-plugin-content-docs/current/intro.md index 404fb77266..4736c2006d 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Beranda" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Pendahuluan +# Stacks Docs -Selamat datang di Dokumentasi Stacks resmi yang digerakkan oleh komunitas. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Belajar tentang penambangan Stacks, token STX, dan bahasa pemrograman kontrak pintar Clarity. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Noda dan Penambang + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/id/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/id/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index 07e71136e4..baf4178b5a 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks di DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Pengantar -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index 979265d7b2..f5b5ba791a 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Noda dan Penambang description: Noda dan Penambang -sidebar_position: 7 +sidebar_position: 5 --- -Berikut adalah semua langkah untuk menjalankan noda dan penambang, baik di mainnet maupun testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## Apa itu noda Stacks? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## Apa itu penambang Stacks? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 499abebafe..822580c447 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Menambang token Stacks mainnet -description: Menyiapkan dan menjalankan penambang di mainnet Stacks 2.0 -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Pengantar -Make sure you've followed the [run a node](run-a-node) procedure. Setelah selesai, tinggal beberapa langkah lagi untuk menjalankan penambang proof-of-burn di mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Menjalankan bitcoind secara lokal +## Running a Bitcoin Mainnet Full Node -Untuk berpartisipasi sebagai penambang di mainnet, Anda harus memiliki akses ke noda bitcoin mainnet. Salah satu cara untuk mencapai ini adalah dengan menjalankan bitcoind secara lokal. [Pastikan komputer Anda memenuhi persyaratan perangkat keras minimum sebelum melanjutkan.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Pertama, unduh perangkat lunak bitcoind untuk platform Anda dari https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Selanjutnya, mulai bitcoind dengan konfigurasi berikut: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Terakhir, mulai bitcoind sebagai berikut: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -Mungkin perlu waktu beberapa hari hingga noda tersebut disinkronkan dengan mainnet Bitcoin. +Next, update the bitcoin configuration: -## Menjalankan penambang - -Pertama, sebuah keychain perlu dibuat. Dengan keychain ini, kita akan membeli beberapa BTC dari pertukaran mata uang kripto, dan kemudian menggunakan BTC tersebut untuk mulai menambang. - -Untuk mendapatkan keychain, cara paling sederhana adalah dengan menggunakan `stacks-cli`. Kita akan menggunakan perintah `make_keychain`. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -Setelah ini berjalan, Anda akan melihat beberapa JSON di file `keychain.txt` baru yang terlihat seperti ini: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Jangan sampai kehilangan informasi ini** - kita harus menggunakan bidang `privateKey`. - -Alamat BTC di atas kemudian perlu diimpor ke jaringan BTC. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Setelah diimpor, kita perlu mendapatkan beberapa BTC ke alamat tersebut. Anda seharusnya dapat mentransfer BTC ke alamat ini menggunakan pertukaran mata uang kripto seperti [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), atau [Kraken](https://www.kraken.com). - - - -Sekarang, kita perlu mengkonfigurasi noda kita untuk menggunakan keychain Bitcoin ini. Kloning [repositori blockchain-stacks](https://github.com/stacks-network/stacks-blockchain) ke mesin lokal Anda jika Anda belum melakukannya. Di folder `blockchain-stacks`, ubah file di [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf /mainnet-miner-conf.toml). - -Perbarui properti berikut: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Masukkan kunci privat Anda di sini -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Sekarang, ambil `privateKey` Anda dari sebelumnya, ketika Anda menjalankan perintah `make_keychain`. Ganti bidang `seed` dengan kunci privat Anda. Simpan dan tutup file konfigurasi ini. +### Start Bitcoin -Untuk menjalankan penambang Anda, jalankan ini di baris perintah: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Noda Anda akan dimulai. Ini akan memakan waktu untuk menyinkronkan, dan kemudian penambang Anda akan berjalan. - -### Membuat biner yang dioptimalkan - -Langkah-langkah di atas sangat bagus untuk mencoba menjalankan noda sementara. Jika Anda ingin menghost noda di server di suatu tempat, Anda mungkin ingin menghasilkan biner yang dioptimalkan. Untuk melakukannya, gunakan konfigurasi yang sama seperti di atas, jalankan: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -Kode di atas akan mengkompilasi biner yang dioptimalkan. Untuk menggunakannya, jalankan: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Aktifkan pencatatan debug - -Jika Anda mengalami masalah atau ingin melihat pencatatan verbose, Anda dapat menjalankan noda dengan pencatatan debug yang diaktifkan. Di baris perintah, jalankan: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Menjalankan penambang di Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Prasyarat +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Membuat keychain dan mendapatkan token mainnet di Windows +### Generate a keychain -Untuk mengatur penambang, pertama-tama kita perlu membuat keychain. Dengan keychain ini, kita akan membeli beberapa BTC dari pertukaran mata uang kripto, dan kemudian menggunakan BTC tersebut untuk mulai menambang. +Pertama, sebuah keychain perlu dibuat. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -Untuk mendapatkan keychain, cara paling sederhana adalah dengan menggunakan `stacks-cli`. Kita akan menggunakan perintah `stx make-keychain`. - -Membuat keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -Setelah ini berjalan, Anda mungkin akan melihat beberapa log instalasi, dan pada akhirnya Anda akan melihat beberapa JSON yang terlihat seperti ini: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ Setelah ini berjalan, Anda mungkin akan melihat beberapa log instalasi, dan pada } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -Alamat BTC di atas kemudian perlu diimpor ke jaringan BTC. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Setelah diimpor, kita perlu mendapatkan beberapa BTC ke alamat tersebut. Anda seharusnya dapat mentransfer BTC ke alamat ini menggunakan pertukaran mata uang kripto seperti [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), atau [Kraken](https://www.kraken.com). -### Perbarui file konfigurasi + + +### Update the Stacks Blockchain Configuration File -Sekarang, kita perlu mengkonfigurasi noda kita untuk menggunakan keychain Bitcoin ini. Kloning [repositori blockchain-stacks](https://github.com/stacks-network/stacks-blockchain) ke mesin lokal Anda jika Anda belum melakukannya. Di folder `blockchain-stacks`, ubah file di [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf /mainnet-miner-conf.toml). +Sekarang, kita perlu mengkonfigurasi noda kita untuk menggunakan keychain Bitcoin ini. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Perbarui properti berikut: +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Simpan dan tutup file konfigurasi ini. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Masukkan kunci privat Anda di sini -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Sekarang, ambil `privateKey` Anda dari sebelumnya, ketika Anda menjalankan perintah `stx make_keychain`. Ganti bidang seed dengan kunci privat Anda. Simpan dan tutup file konfigurasi ini. - -### Jalankan penambang +### Start the Stacks Blockchain -Untuk memulai penambang Anda, jalankan ini di baris perintah: +Untuk menjalankan penambang Anda, jalankan ini di baris perintah: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. Jika demikian, izinkan akses untuk menjalankan noda. -::: ![Windows Defender](/img/windows-defender.png) - Noda Anda akan dimulai. Ini akan memakan waktu untuk menyinkronkan, dan kemudian penambang Anda akan berjalan. -### Aktifkan pencatatan debug pada Windows +### Enable Debug Logging Jika Anda mengalami masalah atau ingin melihat pencatatan verbose, Anda dapat menjalankan noda dengan pencatatan debug yang diaktifkan. Di baris perintah, jalankan: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Opsional: Berjalan dengan Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Atau, Anda dapat menjalankan noda mainnet dengan Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Membuat keychain dan mendapatkan token +### Generate a Keychain and Get Some Tokens Membuat keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -Kita perlu mendapatkan beberapa BTC ke alamat tersebut. Anda seharusnya dapat mentransfer BTC ke alamat ini menggunakan pertukaran mata uang kripto seperti [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), atau [Kraken](https://www.kraken.com). - -### Perbarui file konfigurasi - -Sekarang, kita perlu mengkonfigurasi noda kita untuk menggunakan keychain Bitcoin ini. Kloning [repositori blockchain-stacks](https://github.com/stacks-network/stacks-blockchain) ke mesin lokal Anda jika Anda belum melakukannya. Di folder `blockchain-stacks`, ubah file di [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf /mainnet-miner-conf.toml). - -Perbarui properti berikut: +Kita perlu mendapatkan beberapa BTC ke alamat tersebut. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Masukkan kunci privat Anda di sini -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Sekarang, ambil `privateKey` Anda dari sebelumnya, ketika Anda menjalankan perintah `stx make_keychain`. Ganti bidang seed dengan kunci privat Anda. Simpan dan tutup file konfigurasi ini. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Memulai penambang +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Opsional: Berjalan di Kubernetes dengan Helm -Selain itu, Anda juga dapat menjalankan noda mainnet di klaster Kubernetes menggunakan [bagan Helm blockchain-stacks](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Pastikan Anda telah menginstal prasyarat berikut di mesin Anda: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Hanya diperlukan jika membuat klaster Kubernetes lokal) @@ -313,13 +238,7 @@ Pastikan Anda telah menginstal prasyarat berikut di mesin Anda: ### Membuat keychain dan mendapatkan beberapa token -Membuat keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -Kita perlu mendapatkan beberapa BTC ke alamat tersebut. Anda seharusnya dapat mentransfer BTC ke alamat ini menggunakan pertukaran mata uang kripto seperti [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), atau [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Instal grafik dan jalankan penambang diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index e892bf9c82..70e843114b 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Menambang token Stacks testnet -description: Menyiapkan dan menjalankan penambang di testnet Stacks 2.0 -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Pengantar -Make sure you've followed the [Run a node](run-a-node) procedure. Setelah selesai, tinggal beberapa langkah lagi untuk menjalankan penambang proof-of-burn di testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Menjalankan bitcoind secara lokal +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. Salah satu cara untuk mencapai ini adalah dengan menjalankan bitcoind secara lokal. [Pastikan komputer Anda memenuhi persyaratan perangkat keras minimum sebelum melanjutkan.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -Pertama, unduh perangkat lunak bitcoind untuk platform Anda dari https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Selanjutnya, mulai bitcoind dengan konfigurasi berikut: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Terakhir, mulai bitcoind sebagai berikut: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -Mungkin perlu waktu beberapa jam hingga noda tersebut disinkronkan dengan testnet Bitcoin. - -## Menjalankan penambang - -Pertama, sebuah keychain perlu dibuat. Dengan keychain ini, kita akan mendapatkan beberapa BTC testnet dari faucet, dan kemudian menggunakan BTC tersebut untuk mulai menambang. - -Untuk mendapatkan keychain, cara paling sederhana adalah dengan menggunakan `stacks-cli`. Kita akan menggunakan perintah `make_keychain`, dan meneruskan `-t` untuk menunjukkan bahwa kita menginginkan keychain testnet. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -Setelah ini berjalan, Anda akan melihat beberapa JSON di file `keychain.txt` baru yang terlihat seperti ini: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Jangan sampai kehilangan informasi ini** - kita harus menggunakan bidang `privateKey`. - -Alamat BTC di atas kemudian perlu diimpor ke jaringan testnet BTC. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Setelah diimpor, kita perlu mendapatkan beberapa BTC ke alamat tersebut. Ambil bidang `btcAddress`, dan tempel ke [faucet testnet Bitcoin ini](https://tbtc.bitaps.com/). Anda akan dikirim `0.01` BTC testnet ke alamat tersebut. - -Sekarang, kita perlu mengkonfigurasi noda kita untuk menggunakan keychain Bitcoin ini. Kloning [repositori blockchain-stacks](https://github.com/stacks-network/stacks-blockchain) ke mesin lokal Anda jika Anda belum melakukannya. Di folder `blockchain-stacks`, ubah file di [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf /testnet-miner-conf.toml). - -Perbarui properti berikut: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Sekarang, ambil `privateKey` Anda dari sebelumnya, ketika Anda menjalankan perintah `make_keychain`. Ganti bidang `seed` dengan kunci privat Anda. Simpan dan tutup file konfigurasi ini. - -Untuk menjalankan penambang Anda, jalankan ini di baris perintah: +Terakhir, mulai bitcoind sebagai berikut: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Noda Anda akan dimulai. Ini akan memakan waktu untuk menyinkronkan, dan kemudian penambang Anda akan berjalan. - -### Membuat biner yang dioptimalkan - -Langkah-langkah di atas sangat bagus untuk mencoba menjalankan noda sementara. Jika Anda ingin menghost noda di server di suatu tempat, Anda mungkin ingin menghasilkan biner yang dioptimalkan. Untuk melakukannya, gunakan konfigurasi yang sama seperti di atas, jalankan: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -Kode di atas akan mengkompilasi biner yang dioptimalkan. Untuk menggunakannya, jalankan: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Aktifkan pencatatan debug - -Jika Anda mengalami masalah atau ingin melihat pencatatan verbose, Anda dapat menjalankan noda dengan pencatatan debug yang diaktifkan. Di baris perintah, jalankan: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Menjalankan penambang di Windows +## Running a Stacks Blockchain miner -### Prasyarat +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Membuat keychain dan mendapatkan token testnet di Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -Untuk mengatur penambang, pertama-tama kita perlu membuat keychain. Dengan keychain ini, kita akan mendapatkan beberapa BTC testnet dari faucet, dan kemudian menggunakan BTC tersebut untuk mulai menambang. +### Generate a keychain -Untuk mendapatkan keychain, cara paling sederhana adalah dengan menggunakan `stacks-cli`. Kita akan menggunakan perintah `stx make-keychain`, dan meneruskan `-t` untuk menunjukkan bahwa kita menginginkan keychain testnet. +Pertama, sebuah keychain perlu dibuat. Dengan keychain ini, kita akan mendapatkan beberapa BTC testnet dari faucet, dan kemudian menggunakan BTC tersebut untuk mulai menambang. -Membuat keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -Setelah ini berjalan, Anda mungkin akan melihat beberapa log instalasi, dan pada akhirnya Anda akan melihat beberapa JSON yang terlihat seperti ini: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ Setelah ini berjalan, Anda mungkin akan melihat beberapa log instalasi, dan pada } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Setelah diimpor, kita perlu mendapatkan beberapa BTC ke alamat tersebut. Ambil bidang `btcAddress`, dan tempel ke [faucet testnet Bitcoin ini](https://tbtc.bitaps.com/). Anda akan dikirim `0.01` BTC testnet ke alamat tersebut. -Meminta BTC dari faucet: +### Update the Stacks Blockchain Configuration File -Kita perlu mendapatkan beberapa BTC ke alamat tersebut. Ambil bidang `btcAddress`, dan tempel ke [faucet testnet Bitcoin ini](https://tbtc.bitaps.com/). Anda akan dikirim 0.01 BTC testnet ke alamat tersebut. +Sekarang, kita perlu mengkonfigurasi noda kita untuk menggunakan keychain Bitcoin ini. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Perbarui file konfigurasi +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Simpan dan tutup file konfigurasi ini. -Sekarang, kita perlu mengkonfigurasi noda kita untuk menggunakan keychain Bitcoin ini. Kloning [repositori blockchain-stacks](https://github.com/stacks-network/stacks-blockchain) ke mesin lokal Anda jika Anda belum melakukannya. Di folder `blockchain-stacks`, ubah file di [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf /testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Perbarui properti berikut: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Sekarang, ambil `privateKey` Anda dari sebelumnya, ketika Anda menjalankan perintah `stx make_keychain`. Ganti bidang seed dengan kunci privat Anda. Simpan dan tutup file konfigurasi ini. - -### Jalankan penambang +### Start the Stacks Blockchain -Untuk memulai penambang Anda, jalankan ini di baris perintah: +Untuk menjalankan penambang Anda, jalankan ini di baris perintah: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. Jika demikian, izinkan akses untuk menjalankan noda. -::: ![Windows Defender](/img/windows-defender.png) - - - Noda Anda akan dimulai. Ini akan memakan waktu untuk menyinkronkan, dan kemudian penambang Anda akan berjalan. -### Aktifkan pencatatan debug pada Windows +### Enable Debug Logging Jika Anda mengalami masalah atau ingin melihat pencatatan verbose, Anda dapat menjalankan noda dengan pencatatan debug yang diaktifkan. Di baris perintah, jalankan: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Opsional: Berjalan dengan Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Atau, Anda dapat menjalankan noda testnet dengan Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Membuat keychain dan mendapatkan token testnet +### Generate a Keychain and Get Some Tokens Membuat keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -Kita perlu mendapatkan beberapa BTC ke alamat tersebut. Ambil bidang `btcAddress`, dan tempel ke [faucet testnet Bitcoin ini](https://tbtc.bitaps.com/). Anda akan dikirim 0.01 BTC testnet ke alamat tersebut. - -### Perbarui file konfigurasi +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Sekarang, kita perlu mengkonfigurasi noda kita untuk menggunakan keychain Bitcoin ini. Kloning [repositori blockchain-stacks](https://github.com/stacks-network/stacks-blockchain) ke mesin lokal Anda jika Anda belum melakukannya. Di folder `blockchain-stacks`, ubah file di [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf /testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Perbarui properti berikut: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Sekarang, ambil `privateKey` Anda dari sebelumnya, ketika Anda menjalankan perintah `stx make_keychain`. Ganti bidang seed dengan kunci privat Anda. Simpan dan tutup file konfigurasi ini. - -### Memulai penambang +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,11 +240,13 @@ Anda dapat meninjau log noda dengan perintah ini: docker logs -f stacks_miner ``` +--- + ## Opsional: Berjalan di Kubernetes dengan Helm -Selain itu, Anda juga dapat menjalankan noda testnet di klaster Kubernetes menggunakan [bagan Helm blockchain-stacks](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Pastikan Anda telah menginstal prasyarat berikut di mesin Anda: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Hanya diperlukan jika membuat klaster Kubernetes lokal) @@ -307,24 +255,18 @@ Pastikan Anda telah menginstal prasyarat berikut di mesin Anda: ### Membuat keychain dan mendapatkan beberapa token -Membuat keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` - -Kita perlu mendapatkan beberapa BTC ke alamat tersebut. Ambil bidang `btcAddress`, dan tempel ke [faucet testnet Bitcoin ini](https://tbtc.bitaps.com/). Anda akan dikirim 0.01 BTC testnet ke alamat tersebut. +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Instal grafik dan jalankan penambang Untuk menginstal grafik dengan nama rilis `my-release` dan menjalankan noda sebagai penambang: ```bash -minikube start # Jalankan ini hanya jika berdiri di klaster Kubernetes lokal +minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` Anda dapat meninjau log noda dengan perintah ini: diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 9da4700db8..d90e4377a0 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Konfigurasi Noda Stacks description: Parameter konfigurasi dan opsi untuk biner noda-stacks -sidebar_position: 6 +sidebar_position: 4 --- ## Pemakaian @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subperintah +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Perintah yang tidak digunakan lagi mungkin dapat diakses hingga sepenuhnya dihapus dari sumbernya. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Opsi File Konfigurasi -Memulai noda berdasarkan penyiapan lokal cepat yang meniru burnchain. Ideal untuk pengembangan kontrak pintar. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Contoh: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Contoh: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Deskripsi | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. - -Contoh: - -```bash -stacks-node testnet -``` +:::info This section is _optional_ and not required -### mainnet +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -Memulai noda yang bergabung dan mengalirkan blok dari mainnet publik. +| Name | Required | Deskripsi | +| ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Kunci event yang harus ditonton. Event noda yang dipancarkan dapat dibatasi oleh akun, nama fungsi, dan jenis peristiwa. Asterix ("\*") dapat digunakan untuk memancarkan semua event. | | -Contoh: +### connection_options -```bash -stacks-node mainnet -``` +:::info This section is _optional_ and not required. -### mulai +However, if this section is added, **all** fields are required ::: -Memulai noda dengan konfigurasi Anda sendiri. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Menentukan opsi konfigurasi untuk orang lain yang terhubung ke noda stacks. -#### Argumen +| Name | Required | Deskripsi | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: jalur relatif atau absolut ke file konfigurasi TOML. Diperlukan. +### burnchain -Contoh: +Bagian ini berisi opsi konfigurasi yang berkaitan dengan blockchain yang diikat oleh noda-stacks di backend untuk proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Deskripsi | +| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | Noda-stacks blockchain mengikat pada backend untuk proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | Profil atau fase pengujian untuk menjalankan noda-stacks. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -Lihat [Opsi File Konfigurasi](#configuration-file-options) untuk informasi lebih lanjut. +#### Penambangan -#### versi +| Name | Required | Deskripsi | +| ---------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Menetapkan periode waktu (dalam milidetik) untuk komitmen. Only used when `mode` is set to `mocknet`. | -Menampilkan informasi tentang versi saat ini dan siklus rilis. +### ustx_balance -Contoh: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### bantuan +This section can repeat multiple times, but each section can only define a single address. -Menampilkan pesan bantuan. +:::info This section is only required for the `testnet` and `mocknet` networks. -Contoh: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Deskripsi | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Opsi File Konfigurasi +## Example Mainnet Follower Configuration -File konfigurasi TOML memiliki beberapa bagian di mana opsi dapat ditempatkan. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -Untuk melihat daftar contoh konfigurasi, [lihat halaman ini](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) . +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Bagian: noda +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Berisi berbagai opsi konfigurasi yang berkaitan dengan noda-stacks. -Contoh: + diff --git a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/id/docusaurus-plugin-content-docs/current/references/glossary.md index 53174e2764..9135bc2bf0 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: Daftar lengkap istilah yang digunakan dalam ekosistem. Daftar lengkap istilah yang digunakan dalam ekosistem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Penambangan Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. More information and example [here](../services-using-stacks/wallets). Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 5ad27b2901..54f6823e33 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -1,10 +1,10 @@ --- -title: Situs info Stacks +title: Stacks info sites description: Status and stats of the Stacks network. sidebar_position: 1 --- -Daftar situs berdasarkan abjad yang menampilkan status dan statistik jaringan Stacks. +A list of sites on alphabetical order that display status and stats of the Stacks network. :::tip Are we missing one? Please edit this page to add any relevant new site that we are missing. @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e33ca3010d..42c916c43c 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..2261254023 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Akun +description: Panduan untuk akun Stacks 2.0 +sidebar_position: 7 +--- + +## Pengantar + +Akun dalam Stacks 2.0 adalah suatu entitas yang memiliki aset, seperti token Stacks (STX). Suatu akun memiliki alamat, kunci rahasia, nonce, dan satu atau lebih saldo aset. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Aset tidak bisa meninggalkan suatu akun tanpa tindakan dari pemilik akun. Semua perubahan terhadap aset (dan saldo dari akun) membutuhkan transaksi terkait. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Pembuatan + +Suatu akun dibuat dari frasa 24-kata mnemonic. Hal ini sering disebut juga sebagai **frasa seed**. Frasa seed memberikan akses ke akun Stacks 2.0. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +Cara paling mudah untuk membuat sebuah akun Stacks 2.0 baru adalah dengan [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` membuat file berikut: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Bidang | Deskripsi | +| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mnemonic` | Sebuah frasa seed 240kata digunakan untuk mengakses akun, dibuat menggunakan [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) dengan 256 bit entropi | +| `keyInfo.privateKey` | Kunci privat untuk akun. Dibutuhkan untuk transfer token dan sering dirujuk sebagai `senderKey` | +| `keyInfo.address` | Alamat Stacks untuk akun | +| `keyInfo.btcAddress` | Alamat BTC yang sesuai untuk akun. | +| `keyInfo.wif` | Kunci privat btcAddress dalam format terkompresi. | +| `keyInfo.index` | Nonce untuk akun, dimulai dari 0 | + +Perlu dicatat bahwa akun baru secara otomatis tersedia untuk setiap kunci privat. Tidak perlu memulai proses pembuatan akun di blockchain Stacks 2.0. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. Alamat BTC dikodekan dengan [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). Untuk alamat Stacks, [c32check](https://github.com/stacks-network/c32check) digunakan. Menurunkan suatu alamat dari kunci publik dapat dilakukan tanpa adanya akses internet, contohnya menggunakan metode c32check `c32addressDecode`. ::: + +Sebagai alternatif untuk pembuatan CLI, pustaka [Transaksi Stacks JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) dapat digunakan: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +Alternatif lain dapat menggunakan [stacks-gen](https://github.com/psq/stacks-gen). Alat ini dapat membuat semua kunci yang dibutuhkan dalam satu tempat, termasuk nilai yang dibutuhkan untuk memanggil kontrak stacking, dan juga kunci WIF untuk digunakan dengan `bitcoind`. + +#### prasyarat stacks-gen + +Install [npx](https://github.com/npm/npx) jika belum terpasang. (npx akan mengecek apakah `` sudah ada di \$PATH, atau di daftar file biner proyek lokal dan menjalankannya. Jika `` tidak ditemukan, program akan terpasang sebelum dijalankan). + +``` +npm install -g npx +``` + +#### penggunaan stacks-gen + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Dokumentasi lengkap terdapat di [stacks-gen](https://github.com/psq/stacks-gen). + +## Melakukan query + +### Mendapatkan saldo dan nonce Stacks (STX) + +Saldo dan nonce STX dapat diperoleh melalui [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Contoh respon: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Dapatkan semua saldo token + +Semua saldo token dapat diperoleh melalui [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Contoh respon: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. Cara terbaik untuk mendapatkan saldo BTC yang sesuai adalah dengan mendapatkan alamat BTC dari alamat Stacks (menggunakan [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) dan kueri jaringan Bitcoin. ::: + +### Dapatkan semua event aset + +Semua event aset yang terkait dengan akun dapat diperoleh melalui [`GET /extended/v1/address// aset`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Contoh respon: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..af6dc62b7a --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Autentikasi +description: Daftar dan masuk pengguna menggunakan identitas pada blockchain Stacks +sidebar_position: 8 +--- + +## Pengantar + +Panduan ini menjelaskan bagaimana autentikasi dilakukan pada blockchain Stacks. + +Autentikasi menyediakan cara bagi pengguna untuk mengidentifikasi diri mereka ke aplikasi sambil mempertahankan kontrol penuh atas kredensial dan detail pribadinya. Ini dapat diintegrasikan sendiri atau digunakan bersama dengan [penandatanganan transaksi](https://docs.hiro.so/get-started/transactions#signature-and-verification) dan [penyimpanan data](https://docs.stacks.co/gaia/overview), yang merupakan prasyarat. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## Cara kerjanya + +Alur autentikasi dengan Stacks mirip dengan alur klien-server biasa yang digunakan oleh layanan masuk terpusat (misalnya, OAuth). Namun, dengan Stacks alur autentikasi terjadi sepenuhnya di sisi klien. + +Aplikasi dan autentikator, seperti [Wallet Stacks](https://www.hiro.so/wallet/install-web), berkomunikasi selama alur autentikasi dengan meneruskan dua token. Aplikasi yang melakukan permintaan mengirimkan token `authRequest` kepada autentikator. Setelah pengguna menyetujui autentikasi, autentikator merespons aplikasi dengan token `authResponse`. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. Mereka diteruskan melalui string kueri URL. + +Saat pengguna memilih untuk mengautentikasi aplikasi, itu akan mengirimkan token `authRequest` ke autentikator melalui string kueri URL dengan parameter yang bernama sama yaitu: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +Saat autentikator menerima permintaan, autentikator akan menghasilkan token `authResponse` untuk aplikasi dengan menggunakan _kunci transit sementara_ . Kunci transit sementara hanya digunakan untuk contoh aplikasi tertentu, dalam hal ini, untuk menandatangani `authRequest`. + +Aplikasi menyimpan kunci transit sementara selama pembuatan permintaan. Bagian publik dari kunci transit diteruskan dalam token `authRequest`. Autentikator menggunakan bagian publik dari kunci untuk mengenkripsi _kunci privat aplikasi_ yang dikembalikan melalui `authResponse`. + +Autentikator membuat kunci privat aplikasi dari _identitas alamat kunci privat_ pengguna dan domain aplikasi. Kunci privat aplikasi memiliki tiga fungsi: + +1. Digunakan untuk membuat kredensial yang memberikan akses aplikasi ke keranjang penyimpanan di hub Gaia pengguna +2. Digunakan dalam enkripsi ujung-ke-ujung dari file yang disimpan untuk aplikasi di penyimpanan pengguna Gaia. +3. Berfungsi sebagai rahasia kriptografi yang dapat digunakan aplikasi untuk melakukan fungsi kriptografi lainnya. + +Terakhir, kunci privat aplikasi bersifat deterministik, artinya kunci privat yang sama akan selalu dibuat untuk alamat dan domain Stacks tertentu. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Pasangan kunci + +Autentikasi dengan Stacks akan membuat ekstensif jika menggunakan kriptografi kunci publik secara umum dan ECDSA dengan kurva `secp256k1` secara khusus. + +Bagian berikut menjelaskan tiga pasangan kunci publik-privat yang digunakan, termasuk bagaimana mereka dibuat, di mana mereka digunakan dan kepada siapa kunci privat diungkapkan. + +### Kunci privat transit + +Privat transit adalah kunci sementara yang digunakan untuk mengenkripsi rahasia yang perlu diteruskan dari autentikator ke aplikasi selama proses autentikasi. Ini dibuat secara acak oleh aplikasi di awal respons autentikasi. + +Kunci publik yang sesuai dengan kunci privat transit disimpan dalam susunan elemen tunggal dalam `public_keys` dari token permintaan autentikasi. Autentikator mengenkripsi data rahasia seperti kunci privat aplikasi menggunakan kunci publik ini dan mengirimkannya kembali ke aplikasi saat pengguna masuk ke aplikasi. Kunci privat transit menandatangani permintaan autentikasi aplikasi. + +### Identitas alamat kunci privat + +Identitas alamat kunci privat berasal dari frasa keychain pengguna dan merupakan kunci privat dari nama pengguna Stacks yang dipilih pengguna untuk masuk ke aplikasi. Ini merupakan rahasia yang dimiliki oleh pengguna dan jangan pernah meninggalkan rahasia pengguna dari autentikator. + +Kunci privat ini menandatangani token respons autentikasi untuk aplikasi yang menunjukkan bahwa pengguna telah menyetujui masuk ke aplikasi tersebut. + +### Kunci privat aplikasi + +Kunci privat aplikasi adalah kunci privat khusus aplikasi yang dihasilkan dari identitas alamat kunci privat pengguna menggunakan `domain_name` sebagai masukan. + +Kunci privat aplikasi dibagikan secara aman dengan aplikasi pada setiap autentikasi, dan dienkripsi oleh autentikator dengan kunci publik transit. Karena kunci transit hanya disimpan di sisi klien, ini akan mencegah serangan man-in-the-middle di mana server atau penyedia internet berpotensi mengintip kunci privat aplikasi. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..a4ebf76115 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,241 @@ +--- +title: Bitcoin Name System +description: Mengikat nama pengguna Stacks ke status luar-rantai +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +Blockchain Stacks V1 mengimplementasikan BNS melalui operasi nama urutan pertama. Di Stacks V2, BNS diimplementasikan melalui kontrak pintar yang dimuat selama blok genesis. + +Nama-nama di BNS memiliki tiga properti: + +- **Nama yang unik secara global.** Protokol tidak mengizinkan tubrukan nama, dan semua noda yang berperilaku baik menyelesaikan nama yang diberikan ke status yang sama. +- **Nama memiliki makna yang manusiawi.** Setiap nama dipilih oleh pembuatnya. +- **Nama dimiliki secara penuh.** Hanya pemilik nama yang dapat mengubah statusnya. Secara khusus, sebuah nama dimiliki oleh satu atau lebih kunci privat ECDSA. + +Blockchain Stacks memastikan bahwa tampilan BNS setiap noda disinkronkan ke semua noda lain di dunia, sehingga kueri pada satu noda akan sama pada noda lain. Noda blockchain Stacks memungkinkan pemilik nama untuk mengikat hingga 40Kb keadaan luar-rantai ke nama mereka, yang akan direplikasi ke semua noda blockchain Stacks lainnya melalui jaringan P2P. + +Konsekuensi terbesar bagi pengembang adalah bahwa di BNS, membaca status nama prosesnya akan cepat dan murah namun menulis status nama prosesnya akan lambat dan mahal. Ini karena mendaftarkan dan mengubah nama memerlukan satu atau lebih transaksi untuk dikirim ke blockchain yang mendasarinya, dan noda BNS tidak akan memprosesnya sampai mereka telah dikonfirmasi. Pengguna dan pengembang perlu memperoleh dan membelanjakan mata uang kripto (STX) yang diperlukan untuk mengirim transaksi BNS. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. Ketika Anda mencari situs web, Anda menggunakan Domain Name Service untuk mencari nama host ke alamat IP hostnya. Ketika Anda memeriksa cabang Git, Anda menggunakan klien Git Anda untuk mencari nama cabang ke commit hash. Ketika Anda mencari kunci PGP milik seseorang di keyserver, Anda mencari ID kunci mereka ke kunci publik mereka. + +Hal seperti apa yang kita inginkan untuk menjadi kenyataan mengenai penamaan? Di BNS, nama bersifat unik secara global, nama memiliki makna yang manusiawi, dan nama dimiliki secara penuh. Namun, jika Anda melihat contoh ini, Anda akan melihat bahwa masing-masing hanya menjamin _dua_ properti ini. Ini untuk membatasi seberapa bergunanya mereka. + +- Di DNS dan media sosial, namanya unik secara global dan dapat dibaca oleh manusia, namun tidak dimiliki secara penuh. Operator sistem memiliki keputusan akhir tentang apa yang diputuskan oleh masing-masing nama. + + - **Permasalahan**: Klien harus mempercayai sistem untuk membuat pilihan yang tepat dalam penyelesaian nama yang diberikan. Ini termasuk mempercayai bahwa tidak seorang pun kecuali administrator sistem yang dapat membuat perubahan ini. + +- Di Git, nama cabang memiliki makna yang manusiawi dan dimiliki secara penuh, namun tidak unik secara global. Dua noda Git yang berbeda dapat mencari nama cabang yang sama ke status repositori berbeda yang tidak terkait. + + - **Permasalahan**: Karena nama dapat merujuk ke dalam keadaan yang bertentangan, pengembang harus mencari tahu beberapa mekanisme lain untuk menyelesaikan ambiguitas. Dalam kasus Git, pengguna harus melakukan intervensi secara manual. + +- Di PGP, nama adalah ID kunci. They are globally unique and cryptographically owned, but not human-readable. ID kunci PGP berasal dari kunci yang mereka referensikan. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +Nama BNS memiliki ketiga properti ini, dan tidak memiliki satu permasalahan pun. Ini dapat menjadikannya alat yang ampuh untuk membangun semua jenis aplikasi jaringan. Dengan BNS, kita dapat melakukan hal berikut dan banyak lagi: + +- Membangun domain name services di mana nama host tidak dapat dibajak. +- Membangun platform media sosial di mana nama pengguna tidak dapat dicuri oleh phisher. +- Membangun sistem kontrol versi di mana cabang repositori tidak bertentangan. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organisasi BNS + +Nama BNS diatur ke dalam hierarki nama global. Ada tiga susunan berbeda dalam hierarki ini yang terkait dengan penamaan: + +- **Ruang nama**. Ruang nama adalah nama level teratas dalam hierarki. Sebuah analogi untuk ruang nama BNS adalah domain level atas DNS. Ruang nama BNS yang ada meliputi: `.id`, `.podcast`, dan `.helloworld`. Semua nama lain merupakan milik satu ruang nama. Siapa pun dapat membuat ruang nama, tetapi agar ruang nama tetap ada, ruang nama harus _diluncurkan_ sehingga siapa pun dapat mendaftarkan nama di dalamnya. Ruang nama tidak dimiliki oleh pembuatnya. + +- **Nama BNS**. Nama BNS adalah nama-nama yang catatannya disimpan langsung di blockchain. Kepemilikan dan status nama-nama ini dikontrol dengan mengirimkan transaksi blockchain. Contoh dari nama BNS yaitu `verified.podcast` dan `muneeb.id`. Siapa pun dapat membuat nama BNS, selama ruang nama yang memuatnya sudah ada. + +- **Subdomain BNS**. Subdomain BNS adalah nama-nama yang catatannya disimpan di luar-rantai, tetapi secara kolektif tertaut ke blockchain. Kepemilikan dan status untuk nama-nama ini berada dalam data jaringan P2P. Sementara subdomain BNS dimiliki oleh kunci privat yang terpisah, pemilik nama BNS harus menyiarkan status subdomain mereka. Contoh dari subdomain yaitu `jude.personal.id` dan `podsaveamerica.verified.podcast`. Tidak seperti ruang nama dan nama BNS, status subdomain BNS adalah _bukan_ bagian dari aturan konsensus blockchain. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Fitur | **Ruang nama** | **Nama BNS** | **Subdomain BNS** | +| ---------------------------------------- | -------------- | ------------ | ----------------- | +| Unik secara global | X | X | X | +| Bermakna manusiawi | X | X | X | +| Dimiliki oleh kunci privat | | X | X | +| Siapa pun dapat membuat | X | X | [1] | +| Pemilik bisa memperbarui | | X | [1] | +| Status dihosting secara dalam-rantai | X | X | | +| Status dihosting secara luar-rantai | | X | X | +| Perilaku dikontrol oleh aturan konsensus | X | X | | +| Mungkin memiliki tanggal kedaluwarsa | | X | | + +[1] Memerlukan kerjasama pemilik nama BNS untuk menyiarkan transaksinya + +## Ruang nama + +Namespaces are the top-level name objects in BNS. + +Ruang nama mengontrol beberapa properti tentang nama-nama di dalamnya: + +- Seberapa mahal untuk mendaftar +- Seberapa lama dapat bertahan sebelum harus diperbarui +- Siapa (jika ada) yang menerima biaya pendaftaran nama +- Siapa yang diizinkan untuk menyemai ruang nama dengan nama awalnya. + +Pada saat penulisan ini, ruang nama BNS terbesar adalah ruang nama `.id`. Nama dalam ruang nama `.id` dimaksudkan untuk menyelesaikan identitas pengguna. Nama pendek di `.id` lebih mahal daripada nama panjang, dan harus diperbarui oleh pemiliknya setiap dua tahun. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Tidak seperti DNS, _siapa saja_ dapat membuat ruang nama dan menyetel propertinya. Ruang nama dibuat berdasarkan yang pertama datang yang pertama dilayani, dan setelah dibuat, mereka bertahan selamanya. + +Namun, membuat ruang nama tidak gratis. Pembuat ruang nama harus _membakar_ mata uang kripto untuk melakukannya. Semakin pendek ruang nama, semakin banyak mata uang kripto yang harus dibakar (ruang nama pendek lebih berharga daripada ruang nama panjang). Misalnya, Blockstack PBC 40 BTC membutuhkan biaya untuk membuat ruang nama `.id` pada tahun 2015 (dalam transaksi `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomain + +Nama BNS dimiliki secara penuh karena pemilik dari kunci privatnya dapat menghasilkan transaksi valid yang memperbarui hash dan pemilik file zonanya. Namun, ada biaya yang mengharuskan pemilik nama untuk membayar transaksi yang mendasarinya di blockchain. Selain itu, pendekatan ini membatasi tingkat pendaftaran nama BNS dan operasi ke bandwidth transaksi blockchain yang mendasarinya. + +BNS mengatasi ini melalui subdomain. **Subdomain BNS** adalah jenis nama BNS yang status dan pemiliknya disimpan di luar blockchain, tetapi keberadaan dan riwayat operasinya ditautkan ke blockchain. Seperti rekan-rekan dalam-rantai mereka, subdomain secara global itu unik, dimiliki secara kuat, dan dapat dibaca oleh manusia. BNS memberi mereka nama status dan kunci publik mereka sendiri. Tidak seperti nama dalam-rantai, subdomain dapat dibuat dan dikelola dengan murah, karena mereka disiarkan ke jaringan BNS secara berkelompok. Satu transaksi blockchain dapat mengirim hingga 120 operasi subdomain. + +Ini dicapai dengan menyimpan catatan subdomain dalam file zona nama BNS. Pemilik nama dalam-rantai menyiarkan operasi subdomain dengan mengkodekan sebagai catatan `TXT` dalam file zona DNS. Untuk menyiarkan file zona, pemilik nama menyetel hash file zona baru dengan transaksi `NAME_UPDATE` dan mereplikasi file zona. Pada gilirannya, mereplikasi semua operasi subdomain yang dikandungnya, dan menautkan kumpulan operasi subdomain ke transaksi dalam-rantai. Aturan konsensus noda BNS memastikan bahwa hanya operasi subdomain yang valid dari transaksi _valid_ `NAME_UPDATE` yang akan disimpan. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Setiap catatan `TXT` dalam file zona ini mengkodekan pembuatan subdomain. Misalnya, `1yeardaily.verified.podcast` memutuskan untuk: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Siklus Subdomain + +Perhatikan bahwa `1yeardaily.verified.podcast` memiliki hash (alamat) kunci publik yang berbeda dari `verified.podcast`. Noda BNS hanya akan memproses operasi subdomain berikutnya pada `1yeardaily.verified.podcast` jika noda tersebut menyertakan tanda tangan dari kunci privat alamat ini. `verified.podcast` tidak dapat menghasilkan pembaruan; hanya pemilik `1yeardaily.verified.podcast yang dapat melakukannya`. + +Siklus subdomain dan operasinya ditunjukkan pada Gambar 2. + +``` + pembuatan pembaruan transfer + subdomain subdomain subdomain ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | di-ttd | owner="1Et..." | di-ttd | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | luar-rantai | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | dalam-rantai | | + V V (hash file zona ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blok blok blok + blockchain blockchain blockchain + + +Gambar 2: Masa pakai subdomain sehubungan dengan operasi nama dalam-rantai. Operasi +subdomain baru hanya akan diterima jika memiliki nomor "seqn=" yang lebih baru, +dan tanda tangan yang valid di "sig=" di atas badan transaksi. Bidang "sig=" +mencakup kunci publik dan tanda tangan, serta kunci publik harus hash ke bidang "addr=" +operasi subdomain sebelumnya. + +Transaksi pembuatan subdomain dan transfer subdomain untuk +"cicero.res_publica.id" disiarkan oleh pemilik "res_publica.id." +Namun, nama dalam-rantai mana pun ("jude.id" dalam kasus ini) dapat menyiarkan pembaruan subdomain untuk "cicero.res_publica.id." +``` + +Operasi subdomain diurutkan berdasarkan nomor urut, dimulai dari 0. Setiap operasi subdomain baru harus menyertakan: + +- Nomor urut berikutnya +- Kunci publik yang di-hash ke alamat transaksi subdomain sebelumnya +- A signature from the corresponding private key over the entire subdomain operation. + +Jika dua operasi subdomain yang ditandatangani dengan benar tetapi bertentangan ditemukan (jika mereka memiliki nomor urut yang sama), salah satu yang terjadi lebih awal dalam riwayat blockchain yang akan diterima. Operasi subdomain yang tidak valid akan diabaikan. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Pembuatan dan Pengelolaan Subdomain + +Tidak seperti nama dalam-rantai, pemilik subdomain memerlukan bantuan pemilik nama dalam-rantai untuk menyiarkan operasi subdomain mereka. Khususnya: + +- Transaksi pembuatan subdomain hanya dapat diproses oleh pemilik dari nama dalam-rantai yang berbagi sufiksnya. Misalnya, hanya pemilik `res_publica.id` yang dapat menyiarkan transaksi pembuatan subdomain untuk nama subdomain yang diakhiri dengan `.res_publica.id`. +- Transaksi transfer subdomain hanya dapat disiarkan oleh pemilik nama dalam-rantai yang membuatnya. Misalnya, pemilik `cicero.res_publica.id` membutuhkan pemilik `res_publica.id` untuk menyiarkan transaksi transfer subdomain untuk mengubah kunci publik dari `cicero.res_publica.id`. +- Untuk mengirim pembuatan subdomain atau transfer subdomain, semua file zona pemilik nama dalam-rantai harus ada di jaringan Atlas. Ini memungkinkan noda BNS membuktikan _tidak adanya_ operasi pembuatan subdomain dan transfer subdomain yang bertentangan saat memproses file zona baru. +- Transaksi pembaruan subdomain dapat disiarkan oleh _setiap_ pemilik nama dalam-rantai, tetapi pemilik subdomain perlu menemukan orang yang mau bekerja sama. Misalnya, pemilik `verified.podcast` dapat menyiarkan transaksi pembaruan subdomain yang dibuat oleh pemilik `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Setelah dibuat, pemilik subdomain dapat menggunakan pemilik nama dalam-rantai mana pun untuk menyiarkan operasi pembaruan subdomain. Untuk melakukannya, mereka membuat dan menandatangani operasi subdomain yang diperlukan dan memberikannya kepada pemilik nama dalam-rantai, yang kemudian mengemasnya dengan operasi subdomain lain ke dalam file zona DNS dan menyiarkannya ke jaringan. + +Jika pemilik subdomain ingin mengubah alamat subdomainnya, mereka harus menandatangani operasi transfer subdomain dan memberikannya kepada pemilik nama dalam-rantai yang membuat subdomain. Mereka kemudian mengemasnya ke dalam file zona dan menyiarkannya. + +### Pendaftar Subdomain + +Karena nama subdomain murah, pengembang mungkin cenderung menjalankan pendaftar subdomain atas nama aplikasi mereka. Misalnya, nama `personal.id` digunakan untuk mendaftarkan nama pengguna tanpa mengharuskan mereka membelanjakan Bitcoin apa pun. + +Kami menyediakan implementasi referensi [Pendaftar Subdomain BNS](https://github.com/stacks-network/subdomain-registrar) untuk membantu pengembang menyiarkan operasi subdomain. Pengguna akan tetap memiliki nama subdomain mereka; pendaftar hanya memberi pengembang cara yang nyaman bagi mereka untuk mendaftar dan mengelolanya dalam konteks aplikasi tertentu. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Setiap nama di BNS memiliki DID yang terkait. Format DID untuk BNS adalah: + +```bash + did:stack:v0:{address}-{index} +``` + +Di mana: + +- `{address}` adalah hash kunci publik dalam-rantai (misalnya alamat Bitcoin). +- `{index}` mengacu pada nama `nth` yang dibuat oleh alamat tersebut. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +Contoh lainnya, DID untuk `jude.id` adalah `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Di sini, alamat `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` telah membuat satu nama sebelumnya dalam riwayat sebelum nama ini (yang kebetulan adalah `abcdefgh123456.id`). + +Tujuan DID adalah untuk memberikan pengidentifikasi tak terbatas untuk kunci publik. Kunci publik dapat berubah, namun DID tidak. + +Blockchain Stacks mengimplementasikan metode DID agar kompatibel dengan sistem lain yang menggunakan DID untuk resolusi kunci publik. Agar DID dapat diselesaikan, semua hal berikut harus benar dalam penamaan: + +- Nama harus ada +- Hash file zona nama harus hash dari file zona DNS yang terbentuk dengan baik +- File zona DNS harus ada pada data noda Stacks. +- File zona DNS harus berisi catatan sumber daya `URI` yang mengarah ke JSON Web Token yang ditandatangani +- Kunci publik yang menandatangani Token Web JSON (dan disertakan dengannya) harus di-hash ke alamat yang memiliki nama tersebut + +Tidak semua nama akan memiliki DID yang menjadi kunci publik. Namun, nama yang dibuat oleh alat standar akan memiliki DID yang melakukannya. + +API RESTful sedang dalam pengembangan. + +## DID Encoding for Subdomains + +Setiap nama dan subdomain di BNS memiliki DID. Pengkodean sedikit berbeda untuk subdomain, sehingga perangkat lunak dapat menentukan jalur kode mana yang harus diambil. + +- Untuk nama BNS dalam-rantai, `{address}` sama dengan alamat Bitcoin yang memiliki nama tersebut. Saat ini, alamat versi byte 0 dan versi byte 5 didukung (yaitu, alamat yang dimulai dengan `1` atau `3`, yang artinya `p2pkh` dan alamat `p2sh`). + +- Untuk subdomain BNS luar-rantai, `{address}` memiliki versi byte 63 untuk subdomain yang dimiliki oleh satu kunci privat, dan versi byte 50 untuk subdomain yang dimiliki oleh sekumpulan m-of-n dari kunci privat. Artinya, alamat DID subdomain masing-masing dimulai dengan `S` atau `M`. + +Bidang `{index}` untuk DID subdomain berbeda dari bidang `{index}` untuk DID nama BNS, meskipun nama dan subdomain dibuat sama. Misalnya, nama `abcdefgh123456.id` memiliki DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, karena itu adalah nama depan yang dibuat oleh `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. Namun, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _juga_ membuat `jude.statism.id` sebagai nama subdomain pertamanya. DID untuk `jude.statism.id` adalah `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Perhatikan bahwa alamat `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` mengkodekan hash kunci publik yang sama dengan alamat `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (satu-satunya perbedaan antara dua string ini adalah yang pertama dikodekan base58check dengan versi byte 0, dan yang kedua dikodekan dengan versi byte 63). diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..3bd426a733 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,106 @@ +--- +title: Mikroblok +description: Panduan untuk Mikroblok Stacks +sidebar_position: 5 +--- + +## Pengantar + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Status transaksi + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaksi 1 disiarkan ke mempool. Awalnya memiliki 0 konfirmasi. +Transaksi 1 telah dimasukkan ke dalam mikroblok. Sekarang masih memiliki 0 konfirmasi, namun hasil dari transaksi sudah diketahui. Transaksi 1 telah dimasukan ke dalam blok tertaut berikutnya. Sekarang memiliki 1 konfirmasi. +Blok Stacks berikutnya mengkonfimasi blok sebelumnya. Transaksi 1 sekarang memiliki 2 konfirmasi. +Blok Stacks berikutnya mengkonfimasi blok sebelumnya. Transaksi 1 sekarang memiliki 3 konfirmasi. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaksi 2 disiarkan ke mempool. Awalnya memiliki 0 konfirmasi. +Transaksi 2 telah dimasukkan ke dalam blok tertaut berikutnya. Sekarang memiliki 1 konfirmasi. +Blok Stacks berikutnya mengkonfimasi blok sebelumnya. Transaksi 2 sekarang memiliki 2 konfirmasi. +Blok Stacks berikutnya mengkonfimasi blok sebelumnya. Transaksi 2 sekarang memiliki 3 konfirmasi. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Mengaktifkan mikroblok + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transaksi + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Penambangan + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Mengembangkan dengan mikroblok + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Praktik Terbaik + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Menangani nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Desain Aplikasi + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Penjelajah + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallet + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Bursa + +Continue to count confirmations, microblocks should be considered pending. + +#### Aplikasi + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..10c4409671 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Penambangan +description: Panduan untuk menambang di Stacks 2.0 +sidebar_position: 4 +--- + +## Pengantar + +Panduan ini menggaris bawahi beberapa detail teknis terkait menambang pada jaringan Stacks 2.0. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Frekuensi menambang + +Blok Stacks baru dapat ditambang satu kali per blok Bitcoin. Untuk dapat dipertimbangkan menambang sebuah blok, seorang penambang harus memiliki komit blok yang disertakan dalam blok Bitcoin. Jika penambang ingin memperbarui komitmen mereka setelah pengumpulan, mereka dapat menggunakan Bitcoin Replace-By-Fee. + +## Hadiah coinbase + +Penambang menerima hadiah coinbase untuk blok yang mereka menangkan. + +Jumlah hadiahnya adalah: + +- 1000 STX per blok dikeluarkan pada 4 tahun pertama penambangan +- 500 STX per blok dikeluarkan selama 4 tahun berikutnya +- 250 STX per blok dikeluarkan selama 4 tahun berikutnya +- 125 STX per blok dikeluarkan mulai dari saat itu dan seterusnya. + +"Halving" ini disinkronkan dengan halving Bitcoin. + +![hadiah coinbase](/img/pages/coinbase-rewards.png) + +## Biaya transaksi + +Penambang menerima biaya Stacks untuk transaksi yang ditambang untuk setiap blok yang mereka produksi. + +Untuk transaksi yang ditambang di mikroblok, penambang yang memproduksi mikroblok menerima 40% dari biaya, sedangkan penambang yang mengkonfirmasi mikroblok menerima 60% dari biaya. + +## Maturitas hadiah + +Hadiah blok dan biaya transaksi membutuhkan 100 blok pada jaringan Bitcoin untuk menjadi matur. Setelah berhasil menambang blok, hadiah akan muncul di akun Stacks selama kurang lebih ~24 jam. + +## Menambang menggunakan proof-of-transfer + +Penambang berkomitmen mengeluarkan Bitcoin ke **dua** alamat pada setiap pemilihan ketua blok. Jumlah yang dikomit untuk setiap alamat harus sama. Alamat dipilih dari peserta penerima hadiah stacking saat ini. Alamat dipilih menggunakan fungsi-acak-terverifikasi, dan menentukan dua alamat yang tepat untuk blok tertentu memerlukan pemantauan rantai Stacks. + +![menambang dengan pox](/img/pages/mining-with-pox.png) + +Penambangan PoX adalah modifikasi dari penambangan Proof-of-Burn (PoB), alih-alih mengirim Bitcoin yang berkomitmen ke alamat pembakaran, Bitcoin akan ditransfer ke pemegang STX yang memenuhi syarat yang berpartisipasi dalam protokol stacking. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Alur menambang](/img/pox-mining-flow.png) + +Penambang menjalankan noda Stacks dengan penambangan aktif untuk berpartisipasi dalam mekanisme PoX. Noda mengimplementasikan mekanisme PoX, yang memastikan penanganan dan insentif yang tepat melalui empat fase utama: + +- Pendaftaran: penambang mendaftar untuk pemilihan mendatang dengan mengirimkan data konsensus ke jaringan +- Komitmen: penambang terdaftar mentransfer Bitcoin untuk berpartisipasi dalam pemilihan. BTC yang berkomitmen dikirim ke satu kumpulan pemegang token STX yang berpartisipasi +- Pemilihan: fungsi acak terverifikasi memilih satu penambang untuk menulis blok baru di blockchain Stacks +- Perakitan: penambang terpilih menulis blok baru dan mengumpulkan hadiah dalam bentuk token STX baru + +## Kemungkinan untuk menambang blok berikutnya + +Penambang yang dipilih untuk menambang blok berikutnya dipilih tergantung pada jumlah BTC yang dikirim oleh penambang, yaitu ditransfer atau dibakar. + +Kemungkinan penambang untuk menambang blok berikutnya sama dengan BTC yang dikirim penambang dibagi dengan total BTC yang dikirim oleh semua penambang. + +Meskipun tidak ada komitmen BTC minimum yang diwajibkan oleh protokol, dalam praktiknya, ada batasan yang dibatasi oleh [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": yang pada dasarnya, jika biaya untuk suatu transaksi melebihi nilai pengeluaran yang dikeluarkan, itu dianggap sebagai dust. Bagaimana dust [dihitung](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) tergantung dari beberapa faktor, kita menemukan bahwa 5.500 satoshi adalah batas bawah untuk setiap [keluaran](https://learnmeabitcoin.com/technical/output). Transaksi Bitcoin dari penambang Stacks memiliki dua keluaran (untuk Proof-of-Transfer), jadi suatu komitmen paling tidak 11,000 satoshi / blok yang direkomendasikan. + +Untuk menghitung jumlah BTC yang dikirim penambang harus: + +- Menebak harga BTC/STX untuk hari berikutnya (100 blok kemudian) +- Menebak jumlah BTC yang digunakan oleh semua penambang + +## Mikroblok + +Jaringan blokchain Stacks membuat blok pada kecepatan yang sama seperti blockchain Bitcoin. Untuk menghasilkan latensi transaksi yang lebih rendah, penambang dapat mengaktifkan mikroblok. Mikroblok memungkinkan pemimpin blok saat ini untuk mengalirkan transaksi dan memasukkan status transisinya ke dalam epoch saat ini. + +Jika suatu pemimpin blok memilih untuk memproduksi mikroblok, pemimpin berikutnya harus membuat rantai dari ujung transaksi mikroblok yang pemimpin saat ini hasilkan. + +Model streaming blok dijelaskan di [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..11ab21b3f7 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,148 @@ +--- +title: Jaringan +description: Panduan jaringan Stacks 2.0 +sidebar_position: 5 +--- + +## Token + +Token Stacks (STX) merupakan token native di jaringan blokchain Stacks 2.0. Bagian terkecilnya adalah satu mikro-STX. 1.000.000 mikro-STX sama dengan satu Stacks (STX). + +Jumlah STX harus disimpan sebagai bilangan bulat (panjang 8 bytes), dan mewakili jumlah mikro-STX. Sebagai gambaran, mikro-STX dibagi dengan 1.000.000 (6 digit desimal). + +## Biaya + +Biaya digunakan untuk memberi insentif kepada penambang untuk mengkonfirmasi transaksi di jaringan blockhchain Stacks 2.0. Biaya tersebut dihitung berdasarkan perkiraan tarif biaya dan ukuran transaksi dalam byte. Tingkat biaya adalah variabel yang ditentukan oleh pasar. For the [testnet](testnet), it is set to 1 micro-STX. + +Perkiraan biaya dapat diperoleh melalui endpoint [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer): + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +API akan merespons dengan tarif biaya (sebagai bilangan bulat): + +```json +1 +``` + +[Pustaka Transaksi Stacks JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) mendukung estimasi biaya untuk: + +- transfer token (`estimateTransfer`) +- penyebaran kontrak (`estimateContractDeploy`) +- panggilan kontrak non read-only (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonce + +Setiap akun membawa [properti nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) yang menunjukkan jumlah transaksi yang diproses untuk akun yang diberikan. Nonce adalah kode satu kali, dimulai dari `0` untuk akun baru, dan bertambah 1 pada setiap transaksi. + +Nonce ditambahkan ke semua transaksi dan membantu mengidentifikasinya untuk memastikan transaksi diproses secara berurutan untuk menghindari pemrosesan ganda. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. Pertama, noda mengqueri output transaksi yang tidak terpakai (UTXOs) untuk memenuhi kondisi pengeluaran mereka dalam transaksi baru. Kedua, pesan yang dikirim antar noda meninjau nomor urut. +::: + +Ketika transaksi transfer token baru dibuat, nonce akun terbaru perlu diambil dan diatur. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Konfirmasi + +Jaringan Stacks 2.0 ditautkan ke jaringan bitcoin. Ini memungkinkan transaksi di Stacks untuk mendapat finalitas dan keamanan yang sama dari jaringan blockchain Bitcoin. + +Waktu untuk menambang satu blok, untuk mengkonfirmasi transaksi, pada akhirnya akan sesuai dengan "waktu blok" yang diharapkan dari jaringan bitcoin: 10 menit. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). Waktu blok terkini dapat diperoleh melalui endpoint [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times): + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +API akan merespons dengan waktu blok (dalam detik): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Panggilan fungsi read-only + +Kontrak pintar dapat memperlihatkan panggilan fungsi publik. Untuk fungsi yang membuat modifikasi status pada blockchain, transaksi perlu dibuat dan disebarkan. + +Namun, untuk panggilan fungsi read-only, transaksi **tidak** diperlukan. Sebagai gantinya, panggilan ini dapat dilakukan menggunakan [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +Panggilan kontrak read-only dapat dilakukan menggunakan endpoint [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function): + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +``` + +Contoh respons untuk panggilan yang berhasil: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Melakukan query + +Detail jaringan Stacks 2.0 dapat di-query menggunakan [API Blockchain Stacks](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Cek kesehatan + +[Pemeriksa status](https://stacks-status.com/) adalah layanan yang menyediakan antarmuka pengguna untuk meninjau kesehatan blockchain Stacks 2.0 dengan cepat. + +### Informasi jaringan + +Informasi jaringan dapat diperoleh menggunakan endpoint [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info): + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Contoh respon: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..073bd8ce41 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Memahami mekanisme konsensus proof-of-transfer +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Algoritma konsensus untuk blockchain membutuhkan sumber daya komputasi atau finansial untuk mengamankan blockchain. Praktik umum dari konsensus terdesentralisasi adalah dengan membuatnya secara praktis tidak memungkinkan bagi setiap aktor jahat untuk memiliki kekuatan komputasi yang cukup atau kepemilikan saham untuk menyerang jaringan. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![Mekanisme PoX](/img/pox-mechanism.png) + +Ini memungkinkan peserta jaringan untuk mengamankan jaringan mata uang kripto PoX dan mendapatkan hadiah dalam mata uang kripto dasar. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks menggunakan [Bitcoin](#why-bitcoin) sebagai rantai tertautnya. + +![Peserta PoX](/img/pox-participants.png) + +## Mengapa Bitcoin? + +Ada beberapa alasan mengapa Stacks memilih Bitcoin sebagai blockchain untuk mendukung konsensus. Ini adalah protokol blockchain tertua, yang diluncurkan pada tahun 2009, dan telah menjadi aset yang diakui di luar komunitas mata uang kripto. BTC telah memegang kapitalisasi pasar tertinggi dari semua mata uang kripto selama dekade terakhir ini. + +Bitcoin unggul pada kesederhanaan dan stabilitas, dan telah teruji oleh waktu. Mempengaruhi atau menyerang jaringan akan menjadi sulit atau tidak praktis bagi peretas yang berpotensial. Ini adalah satu-satunya mata uang kripto yang menarik perhatian publik. Bitcoin adalah nama rumah tangga, dan diakui sebagai aset oleh pemerintah, perusahaan besar, dan lembaga perbankan warisan. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 memberikan [daftar lengkap alasan mengapa Bitcoin dipilih untuk mengamankan Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blok dan mikroblok + +Blockchain Stacks memungkinkan peningkatan transaksi melalui mekanisme yang disebut mikroblok. Bitcoin dan Stacks berkembang secara bertahap, dan blok mereka dikonfirmasi secara bersamaan. Di Stacks, ini disebut sebagai 'blok tertaut'. Seluruh blok transaksi Stacks sesuai dengan satu transaksi Bitcoin. Ini secara signifikan meningkatkan rasio biaya/byte untuk memproses transaksi Stacks. Karena produksi blok yang secara simultan, Bitcoin bertindak sebagai pembatas kecepatan untuk membuat blok Stacks, sehingga mencegah serangan penolakan layanan pada jaringan rekanannya. + +Namun, di antara blok terkait Stacks yang menetap di blockchain Bitcoin, ada juga sejumlah mikroblok yang memungkinkan penyelesaian transaksi Stacks secara cepat dengan tingkat kepercayaan yang tinggi. Hal ini memungkinkan transaksi Stacks untuk menskalakan secara independen dari Bitcoin, sambil tetap secara berkala menetapkan finalitas dengan rantai Bitcoin. Blockchain Stacks mengadopsi model streaming blok di mana setiap pemimpin dapat secara adaptif memilih dan mengemas transaksi ke dalam blok mereka saat mereka tiba di mempool. Oleh karena itu ketika blok terkait dikonfirmasi, semua transaksi dalam aliran mikroblok induk dikemas dan diproses. Ini merupakan metode yang belum pernah terjadi sebelumnya untuk mencapai skalabilitas tanpa membuat protokol yang benar-benar terpisah dari Bitcoin. + +![stx-mikroblok](/img/stx-microblocks.png) + +## Membuka kunci modal Bitcoin + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Membuka kunci Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..3e5ef46947 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Pengantar mekanisme hadiah Proof-of-Transfer +sidebar_position: 11 +--- + +## Pengantar + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking merupakan tindakan bawaan, yang diperlukan oleh mekanisme "Proof-of-Transfer" (PoX). The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Alur Stacking + +Mekanisme Stacking dapat disajikan sebagai berikut: + +![Alur Stacking](/img/stacking-illustration.png) + +1. Melakukan panggilan API untuk mendapatkan detail tentang siklus hadiah yang akan datang +2. Untuk akun Stacks tertentu, mengkonfirmasikan kelayakannya +3. Mengkonfirmasikan alamat hadiah BTC dan durasi penguncian +4. Transaksi disebarkan dan token STX dikunci. Ini perlu terjadi sebelum fase persiapan dari siklus hadiah berikutnya, 100 blok Bitcoin terakhir dari fase hadiah yang sedang berlangsung +5. Mekanisme Stacks dalam menjalankan siklus hadiah dan mengirimkan hadiah ke alamat hadiah BTC yang ditetapkan +6. Selama periode penguncian, detail tentang waktu pembukaan kunci, hadiah, dan lainnya dapat diperoleh +7. Setelah periode penguncian berlalu, token dilepaskan dan dapat diakses kembali +8. Menampilkan riwayat hadiah, termasuk detail seperti penghasilan untuk siklus hadiah sebelumnya + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. Durasi ini didasarkan pada waktu blok target jaringan (10 menit) dan bisa lebih tinggi karena [varians waktu konfirmasi](https://www.blockchain.com/charts/median-confirmation-time) dari jaringan bitcoin. ::: + +## Alur pendelegasian Stacking + +Alur Stacking berbeda untuk kasus penggunaan delegasi: + +![Alur pendelegasian Stacking](/img/stacking-delegation-illustration.png) + +- Sebelum Stacking dapat dimulai untuk pemegang token, delegator harus diberikan izin ke Stacks atas nama pemilik akun. Izin dibatasi hingga jumlah maksimum yang diizinkan untuk di-Stack oleh delegator. Jumlah maksimum tidak dibatasi oleh dana yang tersedia dan dapat diatur sehingga jauh lebih tinggi. Sebuah akun hanya dapat diasosiasikan dengan satu delegator +- Akun harus mendefinisikan hubungan delegasi. Mereka secara opsional dapat membatasi alamat hadiah Bitcoin yang harus digunakan untuk pembayaran, dan ketinggian blok bakar kedaluwarsa untuk izin, sehingga membatasi waktu delegator memiliki izin untuk Stack +- Delegator harus mengunci Stacks dari akun yang berbeda ("fase gabungan") hingga mencapai jumlah minimum Stacks yang diperlukan untuk berpartisipasi dalam Stacking +- Setelah delegator mengunci token STX yang cukup, mereka dapat menyelesaikan dan melakukan partisipasi mereka dalam siklus hadiah berikutnya +- Hubungan delegasi tertentu memungkinkan pemegang STX untuk menerima pembayaran langsung dari penambang (langkah 5/6) +- Pemutusan hubungan delegasi dapat terjadi secara otomatis berdasarkan aturan kedaluwarsa yang ditetapkan atau secara aktif mencabut hak delegasi + +## Persyaratan pemegang token + +Pemegang token Stacks (STX) tidak secara otomatis menerima hadiah stacking. Sebaliknya, mereka harus: + +- Komit untuk berpartisipasi sebelum siklus hadiah dimulai +- Komit mengenai jumlah minimum token STX untuk mengamankan slot hadiah, atau menggabungkan dengan orang lain untuk mencapai jumlah minimum +- Mengunci token STX untuk periode tertentu +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +Diagram berikut menjelaskan cara token STX minimal per slot ditentukan. Informasi lebih lanjut tentang [minimal dinamis untuk stacking](https://stacking.club) tersedia di stacking.club. + +![Minimal dinamis untuk kelayakan individu](/img/stacking-dynamic-minimum.png) + +Pemegang token memiliki berbagai penyedia dan alat untuk mendukung partisipasi mereka dalam Stacking. Situs web Stacks berisi [daftar penyedia dan gabungan stacking](https://stacks.org/stacking#earn). + +## Stacking dalam algoritma konsensus PoX + +Stacking adalah kemampuan bawaan PoX dan terjadi melalui serangkaian tindakan pada blockchain Stacks. [Detail implementasi proof-of-transfer lengkap](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) ada di SIP-007. Di bawah ini adalah ringkasan tindakan yang paling relevan dari algoritma. + +![Siklus PoX](/img/pox-cycles.png) + +- Stacking terjadi selama siklus hadiah dengan waktu yang tetap. Dalam setiap siklus hadiah, satu kumpulan alamat Bitcoin yang terkait dengan peserta stacking akan menerima hadiah BTC +- Siklus penghargaan terdiri dari dua fase: persiapan dan penghargaan +- Selama fase persiapan, penambang memutuskan blok terkait dan mengumpulkan hadiah. Menambang cabang turunan dari blok terkait memerlukan transfer dana penambangan ke alamat hadiah yang sesuai. Kumpulan hadiah adalah kumpulan alamat Bitcoin yang memenuhi syarat untuk menerima dana dalam siklus hadiah +- Penambang mendaftar sebagai kandidat pemimpin untuk pemilihan di masa depan dengan mengirimkan transaksi kunci yang dapat membakar mata uang kripto. Transaksi juga mendaftarkan ujung rantai pilihan pemimpin (harus merupakan turunan dari blok terkait) dan komitmen dana ke 2 alamat dari kumpulan hadiah +- Pemegang Token mendaftar untuk siklus hadiah berikutnya dengan menyiarkan pesan yang ditandatangani yang mengunci token STX terkait untuk periode penguncian yang ditentukan protokol, menentukan alamat Bitcoin untuk menerima dana, dan memberikan suara pada ujung rantai Stacks +- Beberapa pemimpin dapat berkomitmen pada ujung rantai yang sama. Pemimpin yang memenangkan pemilihan dan rekan-rekan yang juga mendukung pemimpin itu secara kolektif berbagi hadiah, sebanding dengan berapa banyak yang dibakar oleh masing-masing +- Token yang dikunci pemegang Token secara otomatis akan terbuka setelah periode penguncian selesai + +## Alamat bitcoin + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +Kontrak Stacking memerlukan format khusus untuk alamat Bitcoin (alamat hadiah). Ini diperlukan untuk memastikan bahwa penambang dapat dengan benar membuat transaksi Bitcoin yang berisi alamat hadiah. + +Alamat harus ditentukan dalam format berikut menggunakan bahasa Clarity: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +`versi` buffer harus mewakili jenis alamat bitcoin yang sedang dikirimkan. Ini dapat berupa: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +`Hashbytes` adalah 20 byte hash dari alamat bitcoin. Anda bisa mendapatkannya dari pustaka bitcoin, misalnya menggunakan [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Jenis | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..78b43dfe92 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: API Blockchain Stacks +description: Berinteraksi dengan Blockchain Stacks 2.0 melalui API +sidebar_position: 6 +--- + +## Pengantar +API Blockchain Stacks 2.0 memungkinkan Anda untuk melakukan query blockchain Stacks 2.0 dan berinteraksi dengan kontrak pintar. Dibangun untuk menjaga tampilan halaman dari Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. Untuk dokumentasi lengkap tentang API RESTful, lihat [referensi API Hiro](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. Jalur dasar untuk API adalah: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Endpoint API RPC Noda Stacks yang diproxy +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. Namun, setiap noda Stacks yang berjalan memperlihatkan API RPC, yang memungkinkan Anda berinteraksi dengan blockchain yang mendasarinya. Alih-alih menggunakan API yang dihosting secara terpusat, Anda dapat langsung mengakses API RPC dari noda yang dihosting secara lokal. + +Meskipun Noda RPC API tidak memberikan fungsionalitas yang sama seperti API Blockchain Stacks 2.0 yang dihosting, Anda mendapatkan fungsionalitas serupa dengan cara yang dicakupkan ke noda tertentu. API RPC mencakup endpoint berikut: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. Endpoint info adalah `localhost:20443/v2/info`. ::: diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..10b68c6e4f --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Spesifikasi Teknis +description: Ringkasan spesifikasi teknis Stacks 2.0 +sidebar_position: 13 +--- + +## Konsensus + +- Proof of Transfer (PoX) seperti yang dijelaskan dalam [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Jaringan akan bertransisi ke Proof of Burn (PoB) seperti yang dijelaskan dalam [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) setelah 10 tahun. [Pelajari lebih lanjut tentang Proof-of-Burn di SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Model ancaman + - 51% dari kekuatan penambangan Stacks yang berbahaya dapat melakukan serangan pengeluaran ganda + - 51% dari kekuatan penambangan Bitcoin yang berbahaya dapat mengatur ulang rantai Stacks +- Aktor yang berbeda dan peran mereka + - Penambang Stacks mengemas transaksi ke dalam blok, menambangnya melalui transaksi Bitcoin, menyebarkannya, dan jika mereka memenangkan perlombaan blok, mereka akan menambahkan mikroblok ke blok pemenang mereka hingga blok berikutnya ditambang. Blok berikutnya mengkonfirmasi aliran mikroblok. + - Pemegang Stacks dapat mengubah perhitungan batas blok (yang tunduk pada veto penambang) dan dapat memilih untuk menonaktifkan hadiah Proof-of-Transfer untuk siklus hadiah. +- Transaksi dianggap final ketika transaksi "blok komit" yang sesuai pada Bitcoin diselesaikan. Biasanya sampai dengan 3-6 konfirmasi. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Menambang Proof of Transfer + +- Jadwal hadiah Coinbase: + - 1000 STX/blok untuk 4 tahun pertama + - 500 STX/blok untuk 4 tahun berikutnya + - 250 STX/blok untuk 4 tahun berikutnya + - 125 STX/blok setelahnya +- Hadiah Coinbase terakumulasi untuk "penyortiran yang tidak terjawab": Jika blok Bitcoin tidak memiliki penyortiran (pada ketinggian N), maka blok Stacks apa pun yang ditambang dalam penyortiran berikutnya yang dibangun dari ujung rantai Stacks yang ada pada penyortiran kedua dari belakang (pada ketinggian N- 1) dapat mengklaim codebasenya. Ini mendorong penambang untuk tetap menambang meskipun biaya Bitcoin tinggi. +- Bonus penambangan awal: Ini adalah kasus khusus di atas untuk memberi insentif kepada penambang awal. Coinbase untuk semua blok burnchain antara ketinggian blok pembakaran pertama (akan dipilih oleh penambang independen sebagai bagian dari peluncuran Stacks 2.0) dan pemenang penyortiran pertama terakumulasi dan didistribusikan ke penambang melalui jendela (akan ditentukan). Misalnya, katakanlah tinggi blok bakar adalah 10.000 dan penyortiran pertama berada di blok 10500 dan jendela distribusi adalah 100 blok, maka coinbase untuk 500 blok pertama (10.500 - 10.000) akan didistribusikan secara merata kepada penambang yang memenangkan penyortiran pada 100 blok berikutnya. +- Hadiah maturitas jendela: 100 blok, yang berarti para pemimpin akan mendapatkan hadiah coinbase 100 blok setelah mereka berhasil menambang. +- Interval blok: Blockchain Stacks menghasilkan blok dengan kecepatan yang sama dengan burnchain yang mendasarinya. Untuk Bitcoin, kira-kira setiap 10 menit. +- Komitmen BTC: Penambang harus melakukan setidaknya 11.000 satoshi (5.500 sats / [keluaran UTXO](https://learnmeabitcoin.com/technical/utxo)); 2 keluaran / blok) untuk menghindari "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking terdiri dari 2 fase + 1. Fase persiapan: Dalam fase ini, "blok terkait" dipilih. Kumpulan alamat yang memenuhi syarat ("kumpulan hadiah") ditentukan berdasarkan snapshot dari rantai di blok terkait. Panjang fase persiapan adalah 100 blok. Komitmen stacking perlu dikonfirmasi sebelum fase ini dimulai + 2. Fase hadiah: Dalam fase ini, komitmen BTC penambang didistribusikan di antara kumpulan hadiah. Panjang siklus hadiah adalah 2000 blok BTC (~2 minggu). +- Dua alamat / blok hadiah, dengan total 4000 alamat setiap siklus hadiah. Alamat dipilih menggunakan VRF (fungsi acak terverifikasi), sehingga setiap noda dapat secara deterministik tiba di alamat hadiah yang sama untuk blok yang diberikan. +- Ambang stacking: 0,025% dari jumlah partisipasi STX ketika partisipasi antara 25% dan 100% dan ketika partisipasi di bawah 25%, tingkat ambang selalu 0,00625 dari pasokan likuiditas STX. +- Delegasi: Alamat STX dapat menunjuk alamat lain untuk berpartisipasi dalam Stacking atas namanya. [Bagian yang relevan dalam SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Gabungan: Pemegang STX yang secara individu tidak memenuhi ambang Stacking dapat menggabungkan kepemilikan mereka untuk berpartisipasi dalam Stacking. Untuk melakukan ini, pemegang STX harus mengatur alamat hadiah (opsional) ke "alamat delegasi." Untuk lebih jelasnya, lihat [referensi ini](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Akun dan Alamat + +- Transaksi di blockchain Stacks berasal dari, dibayar oleh, dan dijalankan di bawah otoritas akun +- Sebuah akun sepenuhnya ditentukan oleh alamat + nonce + asetnya +- Alamat berisi 2 atau 3 bidang: versi 1 byte, hash kunci publik 20 byte (RIPEMD160(SHA256(input))), nama opsional (panjang variabel, maks 128 byte) +- Dua jenis akun: akun standar dimiliki oleh satu atau lebih kunci privat; akun kontrak terwujud ketika kontrak pintar dipakai (ditentukan oleh bidang nama opsional di atas) +- Nonce berfungsi menghitung berapa kali akun telah mengotorisasi transaksi. Dimulai dari 0, otorisasi yang valid harus menyertakan nilai nonce _berikutnya_. +- Aset adalah peta semua jenis aset -- STX, semua aset dalam-rantai yang ditentukan oleh kontrak Clarity (misalnya NFT) -- ke dalam jumlah yang dimiliki oleh akun tersebut. +- Akun tidak perlu "dibuat" atau didaftarkan secara eksplisit; semua akun secara implisit ada dan dipakai pada penggunaan pertama. +- Further reading: [Accounts](accounts) + +## Transaksi + +- Jenis transaksi: coinbase, transfer-token, penyebaran kontrak, panggilan kontrak, mikroblok poison. +- Hanya akun standar (bukan kontrak) yang dapat membayar biaya transaksi. +- Eksekusi transaksi diatur oleh 3 akun (mungkin berbeda atau tidak) + 1. _akun asal_ adalah akun yang membuat, _mengotorisasi_ dan mengirimkan transaksi + 2. _akun pembayaran_ adalah akun yang ditagih oleh pimpinan atas biaya validasi dan pelaksanaan transaksi + 3. _akun pengirim_ adalah akun yang mengidentifikasi siapa yang sedang menjalankan transaksi: ini dapat berubah saat transaksi dijalankan melalui fungsi Clarity `sebagai kontrak` +- Transaksi dapat di-batch atau dialirkan ke dalam blok. Perilaku dapat dikendalikan oleh mode terkait transaksi. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Dua jenis otorisasi: otorisasi standar adalah di mana akun asal sama dengan akun pembayaran. Otorisasi _Bersponsor_ adalah perbedaan antara akun asal dan akun pembayaran. Misalnya, pengembang atau penyedia layanan dapat membayar pengguna untuk memanggil kontrak pintar mereka. +- Untuk otorisasi bersponsor, pertama-tama pengguna menandatangani dengan akun asal dan kemudian sponsor menandatangani dengan akun pembayaran. +- Batas Mempool untuk transaksi tertunda bersamaan adalah 25 per akun +- Transaksi mempool yang tertunda akan dikumpulkan setelah [256 blok diterima](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). Dengan waktu blok target 10 menit, ini sama dengan ~42 jam +- [Pelajari lebih lanjut tentang pengkodean transaksi di SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Penandatanganan dan verifikasi transaksi dijelaskan dalam SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- Semua transaksi yang mempengaruhi saldo akun bersifat atomik, operasi transfer tidak dapat menambah saldo satu akun tanpa mengurangi yang lain. Namun, transaksi yang melakukan beberapa tindakan akun (misalnya, mentransfer dari beberapa akun) mungkin sebagian akan selesai. +- Transaksi dapat menyertakan string memo (maks 34 byte) + +## Lihat juga + +- [Baca Stacks 2.0 lengkap: Aplikasi dan Kontrak Pintar untuk whitepaper Bitcoin](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..afed374857 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Uji kontrak dan aplikasi pintar Anda +sidebar_position: 12 +--- + +## Tentang testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. Testnet adalah jaringan yang digunakan oleh pengembang untuk menguji aplikasi, kontrak pintar, atau perubahan protokol mereka dalam lingkungan seperti produksi. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### API testnet + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..2c897fd76f --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transaksi +description: Panduan untuk transaksi Stacks 2.0 +sidebar_position: 9 +--- + +## Pengantar + +Transaksi adalah unit dasar eksekusi di blockchain Stacks. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. Panduan ini akan membantu Anda memahami transaksi Stacks 2.0. + +## Siklus hidup + +Transaksi melewati fase sebelum akhirnya dikonfirmasi, dan tersedia untuk semua, di jaringan Stacks 2.0. + +![Siklus hidup transaksi](/img/tx-lifecycle.png) + +- **Membuat**: Transaksi dibuat sesuai dengan spesifikasi pengkodean. +- **Validasi dan tanda tangan**: Transaksi divalidasi untuk memastikan transaksi dilakukan dengan baik. Tanda tangan diperlukan untuk diisi. +- **Broadcast**: Transaksi dikirim ke noda. +- **Daftar**: Seorang penambang menerima transaksi, memverifikasi, dan menambahkannya ke ["mempool"](https://academy.binance.com/en/glossary/mempool), area penyimpanan untuk semua transaksi yang tertunda. +- **Proses**: Penambang meninjau mempool dan memilih transaksi untuk blok berikutnya yang akan ditambang. Tergantung pada jenis transaksi, tindakan yang berbeda dapat terjadi dalam langkah ini. Misalnya, pasca kondisi dapat diverifikasi untuk transfer token, token yang ditentukan kontrak cerdas dapat dicetak, atau upaya untuk memanggil metode kontrak cerdas yang ada dapat dilakukan. +- **Konfirmasi**: Penambang berhasil menambang blok dengan serangkaian transaksi. Transaksi di dalam berhasil disebarkan ke jaringan. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Tipe + +Stacks 2.0 mendukung serangkaian jenis transaksi yang berbeda: + +| **Jenis** | **Nilai** | **Deskripsi** | +| ------------------ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | Transaksi pertama di blok baru (entitas yang memegang beberapa transaksi). Digunakan untuk mendaftar hadiah blok. Ini tidak dibuat dan disiarkan secara manual seperti jenis transaksi lainnya. | +| Transfer token | `token_transfer` | Transfer aset dari pengirim ke penerima | +| Penyebaran kontrak | `smart_contract` | Instansiasi kontrak | +| Panggilan kontrak | `contract_call` | Panggilan kontrak untuk fungsi publik, non read-only | +| Mikroblok Poison | `poison_microblock` | Menghukum para pemimpin yang dengan sengaja mengelak tentang mikroblok yang telah mereka kemas | + +Contoh setiap jenis transaksi dapat ditemukan di [Definisi respon Stacks Blockchain API untuk transaksi](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/id/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/id/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/id/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/id/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/id/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..e71039e310 --- /dev/null +++ b/i18n/id/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prasyarat + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/id/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/id/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index f130802d8b..b4b6041be9 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## Tentang testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. Testnet adalah jaringan yang digunakan oleh pengembang untuk menguji aplikasi, kontrak pintar, atau perubahan protokol mereka dalam lingkungan seperti produksi. Testnet menghasilkan blok dengan kecepatan yang kira-kira sama dengan mainnet; sekitar 1 blok setiap 10 menit rata-rata. Testnet Stacks jarang diatur ulang. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. Testnet adalah jaringan yang digunakan oleh pengembang untuk menguji aplikasi, kontrak pintar, atau perubahan protokol mereka dalam lingkungan seperti produksi. Testnet menghasilkan blok dengan kecepatan yang kira-kira sama dengan mainnet; sekitar 1 blok setiap 10 menit rata-rata. Testnet Stacks jarang diatur ulang. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/id/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/id/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index 6528bfaac9..6a49a293fd 100644 --- a/i18n/id/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/id/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `concat` function takes two sequences of the same type, and returns a concat ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1382,4 +1387,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..0325c1ac40 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2031 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Importantly, the supplied arguments are evaluated in-order and lazily. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +Also, note that, no matter what kind of sequences the inputs are, the output is always a list. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `func` argument must be a literal function name. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +This hash uniquely identifies Stacks blocks and is unique across Stacks forks. Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. The `time` property returns an integer value of the block header time field. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/ja/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..b2fef628f9 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/ja/docusaurus-plugin-content-docs/current/contribute/translations.md index bd9a452333..fe8f8c6027 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/ja/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2067e7d57c..3f58ca5e68 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/ja/docusaurus-plugin-content-docs/current/gaia/gaia.md index 1070857350..f86a0d61dc 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/ja/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/intro.md b/i18n/ja/docusaurus-plugin-content-docs/current/intro.md index 84f1eaa649..f284f060c8 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Docs Introduction +# Stacks Docs -Welcome to the community driven official Stacks Documentation. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Learn about Stacks mining, the STX token, and the Clarity smart contract language. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..15df918d04 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 061f4a2511..5afd34c23f 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Finally, start bitcoind as follows: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. +Next, update the bitcoin configuration: -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Running a miner in Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Prerequisites +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Generate keychain and get mainnet tokens in Windows +### Generate a keychain -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Update the following properties: +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -313,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index 56374190c1..c0a27e63d5 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -324,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 89af343dc6..cd216e7103 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/glossary.md index 23badef6ac..3f00855d16 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 … ` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). More information and example [here](../services-using-stacks/wallets). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..55d0165def --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..83c5e57cf7 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Register and sign in users with identities on the Stacks blockchain +sidebar_position: 8 +--- + +## Introduction + +This guide explains how authentication is performed on the Stacks blockchain. + +Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## How it works + +The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..9f88fabff4 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,242 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." +``` + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Subdomain Creation and Management + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Each name in BNS has an associated DID. The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..9310aa65be --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..e6e93e130a --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..a0dc623d97 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,148 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a6f9b9ac96 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..ad9bb1822e --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introduction +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..ba6b18f0f7 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/ja/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 59934a5bde..ba6dee45a9 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/ja/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index a6011cca8b..c7708995b6 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `func` argument must be a literal function name. Applicable sequence types a ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1385,4 +1390,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the ```clarity (impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..0325c1ac40 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2031 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Importantly, the supplied arguments are evaluated in-order and lazily. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +Also, note that, no matter what kind of sequences the inputs are, the output is always a list. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `func` argument must be a literal function name. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +This hash uniquely identifies Stacks blocks and is unique across Stacks forks. Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. The `time` property returns an integer value of the block header time field. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/ko/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..b2fef628f9 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/ko/docusaurus-plugin-content-docs/current/contribute/translations.md index bd9a452333..fe8f8c6027 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/ko/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2067e7d57c..3f58ca5e68 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/ko/docusaurus-plugin-content-docs/current/gaia/gaia.md index 1070857350..f86a0d61dc 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/ko/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/intro.md b/i18n/ko/docusaurus-plugin-content-docs/current/intro.md index 84f1eaa649..f284f060c8 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Docs Introduction +# Stacks Docs -Welcome to the community driven official Stacks Documentation. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Learn about Stacks mining, the STX token, and the Clarity smart contract language. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..15df918d04 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 061f4a2511..5afd34c23f 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Finally, start bitcoind as follows: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. +Next, update the bitcoin configuration: -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Running a miner in Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Prerequisites +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Generate keychain and get mainnet tokens in Windows +### Generate a keychain -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Update the following properties: +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -313,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index 56374190c1..c0a27e63d5 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -324,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 89af343dc6..cd216e7103 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/glossary.md index f97908371a..488fbee9b2 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). More information and example [here](../services-using-stacks/wallets). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..55d0165def --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..83c5e57cf7 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Register and sign in users with identities on the Stacks blockchain +sidebar_position: 8 +--- + +## Introduction + +This guide explains how authentication is performed on the Stacks blockchain. + +Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## How it works + +The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..9f88fabff4 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,242 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." +``` + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Subdomain Creation and Management + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Each name in BNS has an associated DID. The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..9310aa65be --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..e6e93e130a --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..a0dc623d97 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,148 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a6f9b9ac96 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..ad9bb1822e --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introduction +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..ba6b18f0f7 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/ko/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 59934a5bde..ba6dee45a9 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/ko/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index a6011cca8b..c7708995b6 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `func` argument must be a literal function name. Applicable sequence types a ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1385,4 +1390,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the ```clarity (impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..ba247ab2f9 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2025 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `true`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. Also, note that, no matter what kind of sequences the inputs are, the output is always a list. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `concat` function takes two sequences of the same type, and returns a concatenated sequence of the same type, with the resulting sequence_len = sequence1_len + sequence2_len. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. This hash uniquely identifies Stacks blocks and is unique across Stacks forks. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +The `time` property returns an integer value of the block header time field. This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (map-get? names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..25fa47305a --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introdução + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..f097d00764 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introdução + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e7ec483a54 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introdução + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/pt/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..ec1b1b0986 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -3,11 +3,11 @@ title: Contribute to docs description: Learn how this site is built, and how you can contribute to it. --- -## Introduction +## Introdução Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/pt/docusaurus-plugin-content-docs/current/contribute/translations.md index 49a9d366ad..fb9977f707 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,24 +1,23 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. -:::caution Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +:::caution Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/pt/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 8f2b139876..93fe3907e1 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -6,7 +6,7 @@ tags: - gaia --- -## Introduction +## Introdução The template provided on this page provides an easy way to deploy a Gaia hub directly to Amazon EC2. You can use this template to deploy your own Gaia hub to your Amazon Web Services (AWS) account. Amazon EC2 is an affordable and convenient cloud computing provider. The template provides a one-click deploy for Amazon EC2 with either S3 or EBS as a storage provider. @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -90,7 +91,9 @@ ssh -i admin@ Open your [AWS Console](https://console.aws.amazon.com) Click on `Service` -> VPC Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/pt/docusaurus-plugin-content-docs/current/gaia/gaia.md index db5f975f8e..ec204e35ec 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- -## Introduction +## Introdução -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/pt/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index 1338c8f865..f034f95503 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,7 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**3. Clone the GAIA repository** and enter it's docker directory. +**3. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -47,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/intro.md b/i18n/pt/docusaurus-plugin-content-docs/current/intro.md index 84f1eaa649..f284f060c8 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Docs Introduction +# Stacks Docs -Welcome to the community driven official Stacks Documentation. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Learn about Stacks mining, the STX token, and the Clarity smart contract language. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..7ed623b977 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- -## Introduction +## Introdução -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 941ff9ac13..5f4ad97634 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- -## Introduction +## Introdução -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` - -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +### Update the Bitcoin Configuration File - +Next, update the bitcoin configuration: -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get mainnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,108 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File + +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. + +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +### Start the Stacks Blockchain -### Run the miner - -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -286,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -301,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -312,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index 1bee3a9923..44eaba22bb 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- -## Introduction +## Introdução -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,106 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +### Start the Stacks Blockchain -### Run the miner - -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -280,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -293,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -323,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 9ea58d7a89..cd216e7103 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/pt/docusaurus-plugin-content-docs/current/references/glossary.md index f97908371a..488fbee9b2 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). More information and example [here](../services-using-stacks/wallets). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..2923ba1b91 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,212 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introdução + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..b00560f5de --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Autenticação +description: Registre e faça login de usuários com identidades no blockchain Stacks +sidebar_position: 8 +--- + +## Introdução + +Este guia explica como a autenticação é realizada na blockchain Stacks. + +A autenticação fornece uma maneira de os usuários se identificarem a um aplicativo, mantendo o controle total sobre suas credenciais e dados pessoais. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite. + +Os usuários que se registrarem em seu aplicativo podem, posteriormente, autenticar em qualquer outro aplicativo com suporte para o sistema de nomes [de Blockchain](bns) e vice-versa. + +## Como isso funciona + +O fluxo de autenticação com Stacks é semelhante ao fluxo típico do servidor cliente-servidor usado por serviços centralizados (por exemplo, OAuth). No entanto, com Stacks o fluxo de autenticação acontece totalmente no lado do cliente. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. O aplicativo de solicitação envia ao autenticador um token `authRequest`. Assim que um usuário aprova a autenticação, o autenticador responde ao aplicativo com um token `authResponse`. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..bd23d43c3e --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,239 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block Figure 2: Subdomain lifetime with respect to on-chain name operations . A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body . The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." +``` + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Subdomain Creation and Management + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Each name in BNS has an associated DID. The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..b178ff03aa --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,106 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introdução + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..27c83c32fa --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,83 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introdução + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..2d1b9585b4 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,149 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +}' +}' +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a1bcf9206e --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,180 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introdução + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. Multiple leaders can commit to the same chain tip. Multiple leaders can commit to the same chain tip. Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..80e7463540 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introdução +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..82aea437f9 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introdução + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/pt/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/pt/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 4fb78f9c06..b20bd11031 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -29,4 +29,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/pt/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index 2acbb0cc93..8769b753b2 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `concat` function takes two sequences of the same type, and returns a concat ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1379,4 +1384,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the ```clarity (impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..0325c1ac40 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2031 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Importantly, the supplied arguments are evaluated in-order and lazily. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +Also, note that, no matter what kind of sequences the inputs are, the output is always a list. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `func` argument must be a literal function name. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +This hash uniquely identifies Stacks blocks and is unique across Stacks forks. Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. The `time` property returns an integer value of the block header time field. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/ru/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..b2fef628f9 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/ru/docusaurus-plugin-content-docs/current/contribute/translations.md index bd9a452333..fe8f8c6027 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/ru/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2067e7d57c..3f58ca5e68 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/ru/docusaurus-plugin-content-docs/current/gaia/gaia.md index 1070857350..f86a0d61dc 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/ru/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/intro.md b/i18n/ru/docusaurus-plugin-content-docs/current/intro.md index 84f1eaa649..f284f060c8 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Docs Introduction +# Stacks Docs -Welcome to the community driven official Stacks Documentation. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Learn about Stacks mining, the STX token, and the Clarity smart contract language. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..15df918d04 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 061f4a2511..5afd34c23f 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Finally, start bitcoind as follows: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. +Next, update the bitcoin configuration: -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Running a miner in Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Prerequisites +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Generate keychain and get mainnet tokens in Windows +### Generate a keychain -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Update the following properties: +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -313,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index 56374190c1..c0a27e63d5 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -324,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 40b2ef676b..cd216e7103 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` +Specifies configuration options for others connecting to the stacks node. -### start +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +### burnchain -#### Arguments +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -**--config**: relative or absolute path to the TOML config file. Required. +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -Example: +#### Mining -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -See [Configuration File Options](#configuration-file-options) for more information. +### ustx_balance -#### version +- `mocknet`/`testnet` only -Displays information about the current version and the release cycle. +This section contains configuration options allocating microSTX per address in the genesis block -Example: +This section can repeat multiple times, but each section can only define a single address. -```bash -stacks-node version -``` +:::info This section is only required for the `testnet` and `mocknet` networks. -#### help +However, if this section is added, **all** fields are required ::: -Displays a help message. +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -Example: +## Example Mainnet Follower Configuration -```bash -stacks-node help -``` - -## Configuration File Options - -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/ru/docusaurus-plugin-content-docs/current/references/glossary.md index f97908371a..488fbee9b2 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). More information and example [here](../services-using-stacks/wallets). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..55d0165def --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..83c5e57cf7 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Register and sign in users with identities on the Stacks blockchain +sidebar_position: 8 +--- + +## Introduction + +This guide explains how authentication is performed on the Stacks blockchain. + +Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## How it works + +The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..9f88fabff4 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,242 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." +``` + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Subdomain Creation and Management + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Each name in BNS has an associated DID. The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..9310aa65be --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..e6e93e130a --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..dd50cb7ee1 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,151 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +}' +}' +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a6f9b9ac96 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..ad9bb1822e --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introduction +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..ba6b18f0f7 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/ru/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 59934a5bde..ba6dee45a9 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/ru/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index a6011cca8b..c7708995b6 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `func` argument must be a literal function name. Applicable sequence types a ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1385,4 +1390,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the ```clarity (impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..0325c1ac40 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2031 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Importantly, the supplied arguments are evaluated in-order and lazily. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +Also, note that, no matter what kind of sequences the inputs are, the output is always a list. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `func` argument must be a literal function name. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +This hash uniquely identifies Stacks blocks and is unique across Stacks forks. Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. The `time` property returns an integer value of the block header time field. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/tr/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..b2fef628f9 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/tr/docusaurus-plugin-content-docs/current/contribute/translations.md index bd9a452333..fe8f8c6027 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/tr/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2067e7d57c..3f58ca5e68 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/tr/docusaurus-plugin-content-docs/current/gaia/gaia.md index 1070857350..f86a0d61dc 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/tr/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/intro.md b/i18n/tr/docusaurus-plugin-content-docs/current/intro.md index ea521dd1f5..f284f060c8 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Ana sayfa" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Dokümanları Tanıtımı +# Stacks Docs -Topluluk odaklı resmi Stacks Dokümantasyonuna hoş geldiniz. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Stacks madenciliği, STX token ve Clarity akıllı sözleşme dili hakkında bilgi edinin. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..15df918d04 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 061f4a2511..5afd34c23f 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Finally, start bitcoind as follows: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. +Next, update the bitcoin configuration: -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Running a miner in Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Prerequisites +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Generate keychain and get mainnet tokens in Windows +### Generate a keychain -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Update the following properties: +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -313,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index 56374190c1..c0a27e63d5 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -324,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 89af343dc6..cd216e7103 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/tr/docusaurus-plugin-content-docs/current/references/glossary.md index f97908371a..488fbee9b2 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). More information and example [here](../services-using-stacks/wallets). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..55d0165def --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..83c5e57cf7 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Register and sign in users with identities on the Stacks blockchain +sidebar_position: 8 +--- + +## Introduction + +This guide explains how authentication is performed on the Stacks blockchain. + +Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## How it works + +The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..9f88fabff4 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,242 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." +``` + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Subdomain Creation and Management + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Each name in BNS has an associated DID. The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..9310aa65be --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..e6e93e130a --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..a0dc623d97 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,148 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a6f9b9ac96 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..ad9bb1822e --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introduction +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..ba6b18f0f7 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/tr/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/tr/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 59934a5bde..ba6dee45a9 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/tr/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/tr/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index a6011cca8b..c7708995b6 100644 --- a/i18n/tr/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/tr/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `func` argument must be a literal function name. Applicable sequence types a ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1385,4 +1390,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the ```clarity (impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..a90f91b599 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..32989bba8e --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2028 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `true`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. Also, note that, no matter what kind of sequences the inputs are, the output is always a list. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `concat` function takes two sequences of the same type, and returns a concatenated sequence of the same type, with the resulting sequence_len = sequence1_len + sequence2_len. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` + +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` + +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. This hash uniquely identifies Stacks blocks and is unique across Stacks forks. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +The `time` property returns an integer value of the block header time field. This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (map-get? names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (get-balance (account principal)) + (ok u0)) +(define-public (transfer? (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..1aca5359c3 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..0af4577dc9 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/vi/docusaurus-plugin-content-docs/current/contribute/docs.md index 77705451b8..b2fef628f9 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Write [in plain text an issue on Github](htt :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -204,4 +210,4 @@ Some **content** with _markdown_ `syntax`. Some **content** with _markdown_ `syntax`. -::: \ No newline at end of file +::: diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/vi/docusaurus-plugin-content-docs/current/contribute/translations.md index bd9a452333..fe8f8c6027 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,25 +1,24 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. All help is appreciated. :::caution -Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. +Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/vi/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2067e7d57c..3f58ca5e68 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/vi/docusaurus-plugin-content-docs/current/gaia/gaia.md index 1070857350..f86a0d61dc 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/vi/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index db427f890a..2c0ca2b92e 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with: +**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. +**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/intro.md b/i18n/vi/docusaurus-plugin-content-docs/current/intro.md index 84f1eaa649..f284f060c8 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Docs Introduction +# Stacks Docs -Welcome to the community driven official Stacks Documentation. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Learn about Stacks mining, the STX token, and the Clarity smart contract language. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index dd7194f504..15df918d04 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: Stacks on DigitalOcean +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! You are now running the Stacks Blockchain. You can click on `Co ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 468a01df66..5afd34c23f 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,166 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -Finally, start bitcoind as follows: +### Update the Bitcoin Configuration File -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. +Next, update the bitcoin configuration: -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC network. - -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: +--- -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +## Running a Stacks Blockchain miner -## Running a miner in Windows +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -### Prerequisites +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -### Generate keychain and get mainnet tokens in Windows +### Generate a keychain -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command. - -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -174,109 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` + + Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + + +### Update the Stacks Blockchain Configuration File -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -Update the following properties: +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) ```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -```toml -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -287,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -302,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -313,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index b572df3ba2..c0a27e63d5 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,126 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command, and pass `-t` to indicate that we want a testnet keychain. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. - -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +### Start Bitcoin -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -170,107 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: + +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: + +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` + +Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. -Request BTC from faucet: +### Update the Stacks Blockchain Configuration File -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -### Update configuration file +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +Next, update the bitcoin configuration: -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) ```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. - -### Update config file +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: @@ -281,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -294,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -324,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index 89af343dc6..cd216e7103 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/vi/docusaurus-plugin-content-docs/current/references/glossary.md index 1027a52c96..20474763a7 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. More information and example [here](../services-using-stacks/wallets). Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index 51defacba7..58717a3234 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index df0b3e2254..1e14b9a5a5 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index bfa0505dc9..d582604854 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -15,16 +15,25 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 35ced8dac6..54f6823e33 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index e5ea6c5b45..80142a29d1 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -15,6 +15,7 @@ Please edit this page to add any relevant new site that we are missing. [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..55d0165def --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,215 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..59a8929797 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Register and sign in users with identities on the Stacks blockchain +sidebar_position: 8 +--- + +## Introduction + +This guide explains how authentication is performed on the Stacks blockchain. + +Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/gaia/overview), for which it is a prerequisite. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## How it works + +The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..9f88fabff4 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,242 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." +``` + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. + +Combined, this ensures that a BNS node with all of the zone files with a given subdomain's operations will be able to determine the valid sequence of state-transitions it has undergone, and determine the current zone file and public key hash for the subdomain. + +### Subdomain Creation and Management + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +BNS names are compliant with the emerging [Decentralized Identity Foundation](http://identity.foundation) protocol specification for decentralized identifiers (DIDs). + +Each name in BNS has an associated DID. The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. For example, the name `abcdefgh123456.id` has the DID `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-0`, because it was the first name created by `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg`. However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..9310aa65be --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..e6e93e130a --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..a0dc623d97 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,148 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..50f4b739d6 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..a6f9b9ac96 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..ad9bb1822e --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introduction +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..6f9fe1599e --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..ba6b18f0f7 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/vi/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/vi/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 59934a5bde..ba6dee45a9 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/vi/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/vi/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index 4605b2f4c9..10727f2566 100644 --- a/i18n/vi/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/vi/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -349,7 +354,7 @@ The `concat` function takes two sequences of the same type, and returns a concat ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` @@ -628,7 +633,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1382,4 +1387,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/crash-course.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/crash-course.md new file mode 100644 index 0000000000..836fe1b158 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/crash-course.md @@ -0,0 +1,122 @@ +--- +title: Clarity Crash Course +description: A quick introduction to the Clarity programming language +sidebar_position: 1 +--- + +You now understand why Clarity exists and what problems it was designed to solve. :::note +If you didn't read the previous section, go ahead and [do that first](./index.md). +::: + +Now let's do a really quick introduction to Clarity so you can familiarize yourself with the language and syntax. + +This crash course is designed for people who have some experience with programming but are new to Clarity. You don't need smart contract development experience, but if you do, with something like Solidity, you'll pick this up really quick. + +Once you've familiarized yourself with the language, if you'd like to continue your journey and master Clarity to become a smart contract developer, we recommend either the book, [Clarity of Mind](https://book.clarity-lang.org/title-page.html), or the course, [Clarity Universe](https://clarity-lang.org/universe), which has both a self-paced and guided cohort-based version. + +## Your First Clarity Smart Contract + +We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. + +Visit that link, and it will open up a new contract for you. + +![Clarity Tools New](tools-new.png) + +Already we can take a look at a few basic features of both Clarity and Clarity Tools. First, on the left you'll see that our Clarity code is being evaluated in real-time for us. This is really nice for experimenting and demonstrating basic Clarity code. + +Next up we can see our first bit of Clarity code. + +Those two semicolons are how we denote comments in Clarity. + +Then the next line down we have a public function declaration. + +Here is out first glimpse of Clarity's syntax, which may be new to you depending on your development background. + +For those new to Clarity, it's a little weird and uncomfortable at first, but one of the core design tenets of Clarity is simplicity and readability, and the more you work with it the more you come to appreciate the succinctness and _clarity_ (sorry) of the code you are writing. + +Clarity takes inspiration from LISP, and you can think of everything in Clarity as a list inside of a list, or an expression inside of an expression. Everything in Clarity is wrapped in parentheses, function definitions, variable declarations, function parameters, etc. + +So here we are saying that we want to: + +1. Call a function called `define-read-only`. This is a built-in function, one of many that you can refer to [in the docs](./language-functions.mdx). + +2. Pass it a parameter of hello, which corresponds to the method signature type. + +3. Pass it a parameter of "Hello", which corresponds to the function body. + +You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation to see these parameters. + +Why am I describing this as if we are calling a function? Because we are, and it's an important concept in Clarity that everything is an expression inside of an expression. + +Let's expand on this concept a bit by deleting this and writing a new function. + +```clarity +(define-data-var count int 0) +(define-public (add-number (number int)) + (let + ( + (current-count count) + ) + + (var-set count (+ 1 number)) + (ok (var-get count)) + ) +) + + +(add-number 5) +``` + +If you type that into Clarity Tools, you'll see the result that gets printed is 6. + +![Clarity Tools New](tools-new.png) + +Okay there are actually a lot of Clarity concepts packed into this simple code. + +Let's go over what this code is doing, and you'll pick up some Clarity concepts along the way. + +The first thing we are doing here is defining a new variable called `count` and setting its initial value to 0. + +This will be a persistent state variable, so this is actually getting written to the blockchain. If you are new to smart contract development, the fact that data is persisted within the file like this might take some getting used to. + +So if we were to write and deploy this contract (which you can do in the Stacks Explorer if you like), as soon as it gets deployed, it will run through the contract line by line executing anything at the root level. + +Remember that Clarity is interpreted, not compiled, so there's not compile step when developing Clarity contracts. + +So this `define-data-var` will be evaluated and the `count` variable will be initialized with a value of 0. + +Next we are defining a public function called `add-number`, which will be created (but not called) on deploy as well. + +:::note +In Clarity, we have public, private, and read only functions. Public allow you to modify chain state and can be called from anywhere, private do the same except they can only be called from within the contract, and read only will fail if they attempt to modify state. +::: + +This function is taking a single parameter, called `number` that is a type of `int`. + +Now, what is this `let` business all about? Remember that we said that everything in Clarity is an expression and declaring new functions is just a matter of calling the `define-public` function? + +Well the second argument to this is the function body, but it can only evaluate a single expression. + +So this `let` function is a way of wrapping a multi-step function into a single argument. + +But it does one other crucial thing at the beginning. This line: + +```clarity +(current-count count) +``` + +Sets a variable that only exists in the context of this particular function. So here we are saying, create a new variable called `current-count` and set it equal to the value of `count`. + +Then we use that in our actual function body down below. + +In the next step we are setting the value of our `count` variable to 1 plus whatever number we passed in. The `+` is just another call to a function where the parameters are the numbers we want to add. + +Then, finally, we are returning the new value of `count` with our `ok` response, indicating that the function completed successfully. + +Then in the very last line we are actually calling this function, passing in 5. + +This was a very brief overview of Clarity just to get your feet wet and give you a taste of how it works. + +If you are interested in diving into the details, we highly recommend going through either the [Clarity Book](https://book.clarity-lang.org/title-page.html) or [Clarity Universe](https://clarity-lang.org/universe), depending on your learning style. + +If you prefer to dive directly into the docs, you can continue on ahead and check out the types, keywords, and functions available in Clarity, as well as a few sample contracts. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/index.md new file mode 100644 index 0000000000..2426916d2c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/index.md @@ -0,0 +1,58 @@ +--- +title: Clarity Overview +description: Overview and guides for getting started with Clarity +sidebar_label: Clarity +sidebar_position: 5 +--- + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, designed for the Stacks blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. Smart contracts allow developers to encode essential business logic on a blockchain. + +The design decisions behind Clarity were based heavily on taking lessons learned in common Solidity exploits and creating a language that has been purpose-built for safety and security in mind. + +These docs serve primarily as a reference for the functions and keywords that you can use in Clarity. + +In order to learn Clarity, we recommend diving into the [Clarity of Mind](https://book.clarity-lang.org/), an online book to teach you everything you need to know to build robust smart contracts, or joining a [Clarity Camp](https://clarity-lang.org/universe#camp), the cohort-based immersive Clarity experience. + +## What makes Clarity different + +The following section is an excerpt from the excellent book, [Clarity of Mind](https://book.clarity-lang.org/ch00-00-introduction.html): + +The number of smart contract languages grows by the year. Choosing a first language can be challenging, especially for a beginner. The choice is largely dictated by the ecosystem you are interested in, although some languages are applicable to more than just one platform. Each language has its own upsides and downsides and it is out of the scope of this book to look at all of them. Instead, we will focus on what sets Clarity apart and why it is a prime choice if you require the utmost security and transparency. + +One of the core precepts of Clarity is that it is secure by design. The design process was guided by examining common pitfalls, mistakes, and vulnerabilities in the field of smart contract engineering as a whole. There are countless real world examples of where developer failure led to the loss or theft of vast amounts of tokens. To name two big ones: an issue that has become known as the Parity bug led to the irreparable loss of millions of dollars worth of Ethereum. Second, the hacking of The DAO (a "Decentralized Autonomous Organization") caused financial damage so great that the Ethereum Foundation decided to issue a contentious hard fork that undid the theft. These and many other mistakes could have been prevented in the design of the language itself. + +### Clarity is interpreted, not compiled + +Clarity code is interpreted and committed to the chain exactly as written. Solidity and other languages are compiled to byte-code before it is submitted to the chain. The danger of compiled smart contract languages is two-fold: first, a compiler adds a layer of complexity. A bug in the compiler may lead to different byte-code than was intended and thus carries the risk of introducing a vulnerability. Second, byte-code is not human-readable, which makes it very hard to verify what the smart contract is actually doing. Ask yourself, would you sign a contract you cannot read? If your answer is no, then why should it be any different for smart contracts? With Clarity, what you see is what you get. + +### Clarity is decidable + +A decidable language has the property that from the code itself, you can know with certainty what the program will do. This avoids issues like the halting problem. With Clarity you know for sure that given any input, the program will halt in a finite number of steps. In simple terms: it is guaranteed that program execution will end. Decidability also allows for complete static analysis of the call graph so you get an accurate picture of the exact cost before execution. There is no way for a Clarity call to "run out of gas" in the middle of the call. We explore this idea more, along with a discussion on Turing completeness, in the [security deep dive on decidability](./security/decidable.md). + +### Clarity does not permit reentrancy + +Reentrancy is a situation where one smart contract calls into another, which then calls back into the first contract—the call "re-enters" the same logic. It may allow an attacker to trigger multiple token withdrawals before the contract has had a chance to update its internal balance sheet. Clarity's design considers reentrancy an anti-feature and disallows it on the language level. + +### Clarity guards against overflow and underflows + +Overflows and underflows happen when a calculation results in a number that is either too large or too small to be stored, respectively. These events throw smart contracts into disarray and may intentionally be triggered in poorly written contracts by attackers. Usually this leads to a situation where the contract is either frozen or drained of tokens. Overflows and underflows of any kind automatically cause a transaction to be aborted in Clarity. + +### Support for custom tokens is built-in + +Issuance of custom fungible and non-fungible tokens is a popular use-case for smart contracts. Custom token features are built into the Clarity language. Developers do not need to worry about creating an internal balance sheet, managing supply, and emitting token events. Creating custom tokens is covered in depth in later chapters. + +### On Stacks, transactions are secured by post conditions + +In order to further safeguard user tokens, post conditions can be attached to transactions to assert the chain state has changed in a certain way once the transaction has completed. For example, a user calling into a smart contract may attach a post condition that states that after the call completes, exactly 500 STX should have been transferred from one address to another. If the post condition check fails, then the entire transaction is reverted. Since custom token support is built right into Clarity, post conditions can also be used to guard any other token in the same way. + +### Returned responses cannot be left unchecked + +Public contract calls must return a so-called response that indicates success or failure. Any contract that calls another contract is required to properly handle the response. Clarity contracts that fail to do so are invalid and cannot be deployed on the network. Other languages like Solidity permit the use of low level calls without requiring the return value to be checked. For example, a token transfer can fail silently if the developer forgets to check the result. In Clarity it is not possible to ignore errors, although that obviously does prevent buggy error handling on behalf of the developer. Responses and error handling are covered extensively in the chapters on functions and control flow. + +### Composition over inheritance + +Clarity adopts a composition over inheritance. It means that Clarity smart contracts do not inherit from one another like you see in languages like Solidity. Developers instead define traits which are then implemented by different smart contracts. It allows contracts to conform to different interfaces with greater flexibility. There is no need to worry about complex class trees and contracts with implicit inherited behavior. + +### Access to the base chain: Bitcoin + +Clarity smart contracts can read the state of the Bitcoin base chain. It means you can use Bitcoin transactions as a trigger in your smart contracts! Clarity also features a number of built-in functions to verify secp256k1 signatures and recover keys. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-functions.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-functions.md new file mode 100644 index 0000000000..b61ee10ae6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-functions.md @@ -0,0 +1,2032 @@ +--- +title: Functions +description: See a detailed list of all functions for the Clarity language. +sidebar_position: 3 +tags: + - clarity +--- + +## Functions + +Detailed list of all functions for the Clarity language. + +### + (add) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(+ i1 i2...)` + +#### description: + +Adds a variable number of integer inputs and returns the result. Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(+ 1 2 3) ;; Returns 6 +(+ 2 3) ;; Returns 5 +(+ 1 2 3 4) ;; Returns 10 +(+ 9 -3) ;; Returns 6 +(+ -3 -2) ;; Returns -5 +``` + +### - (subtract) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(- i1 i2...)` + +#### description: + +Subtracts a variable number of integer inputs and returns the result. Subtracts a variable number of integer inputs and returns the result. In the event of an _underflow_, throws a runtime error. + +#### example: + +```clarity +(- 2 1 1) ;; Returns 0 +(- 0 3) ;; Returns -3 +(- 5 -3) ;; Returns 8 +(- -4 -5) ;; Returns 1 +``` + +### \* (multiply) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(* i1 i2...)` + +#### description: + +Multiplies a variable number of integer inputs and returns the result. Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(* 2 3) ;; Returns 6 +(* 5 2) ;; Returns 10 +(* 2 2 2) ;; Returns 8 +(* 3 -2) ;; Returns -6 +(* -1 -2) ;; Returns 2 +``` + +### / (divide) + +#### input: `int, ... | uint, ...` + +#### output: `int | uint` + +#### signature: `(/ i1 i2...)` + +#### description: + +Divides a variable number of integer inputs and returns the _integer part_ of the result. In the event of _division by zero_, throws a runtime error. + +#### example: + +```clarity +(/ 2 3) ;; Returns 0 +(/ 5 2) ;; Returns 2 +(/ 4 2 2) ;; Returns 1 +(/ -10 2) ;; Returns -5 +(/ -8 -2) ;; Returns 4 +(/ -9 4) ;; Returns -2 +``` + +### >= (greater than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(>= i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(>= 1 1) ;; Returns true +(>= 5 2) ;; Returns true +``` + +### <= (less than or equal) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(<= i1 i2)` + +#### description: + +Compares two integers, returning true if `i1` is less than or equal to `i2` and `false` otherwise. + +#### example: + +```clarity +(<= 1 1) ;; Returns true +(<= 5 2) ;; Returns false +``` + +### < (less than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(< i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is less than `i2` and `false` otherwise. + +#### example: + +```clarity +(< 1 2) ;; Returns true +(< 5 2) ;; Returns false +``` + +### > (greater than) + +#### input: `int, int | uint, uint` + +#### output: `bool` + +#### signature: `(> i1 i2)` + +#### description: + +Compares two integers, returning `true` if `i1` is greater than `i2` and false otherwise. + +#### example: + +```clarity +(> 1 2) ;; Returns false +(> 5 2) ;; Returns true +``` + +### to-int + +#### input: `uint` + +#### output: `int` + +#### signature: `(to-int u)` + +#### description: + +Tries to convert the `uint` argument to an `int`. Tries to convert the `uint` argument to an `int`. Will cause a runtime error and abort if the supplied argument is >= `pow(2, 127)`` + +#### example: + +```clarity +(to-int u238) ;; Returns 238 +``` + +### to-uint + +#### input: `int` + +#### output: `uint` + +#### signature: `(to-uint i)` + +#### description: + +Tries to convert the `int` argument to a `uint`. Will cause a runtime error and abort if the supplied argument is negative. + +#### example: + +```clarity +(to-uint 238) ;; Returns u238 +``` + +### mod + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(mod i1 i2)` + +#### description: + +Returns the integer remainder from integer dividing `i1` by `i2`. In the event of a division by zero, throws a runtime error. + +#### example: + +#### example: + +```clarity +(mod 2 3) ;; Returns 2 +(mod 5 2) ;; Returns 1 +(mod 7 1) ;; Returns 0 +``` + +### pow + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(pow i1 i2)` + +#### description: + +Returns the result of raising `i1` to the power of `i2`. Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. + +#### example: + +```clarity +(pow 2 3) ;; Returns 8 +(pow 2 2) ;; Returns 4 +(pow 7 1) ;; Returns 7 +``` + +### sqrti + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(sqrti n)` + +#### description: + +Returns the largest integer that is less than or equal to the square root of `n`. Fails on a negative numbers. Fails on a negative numbers. + +#### example: + +```clarity +(sqrti u11) ;; Returns u3 +(sqrti 1000000) ;; Returns 1000 +(sqrti u1) ;; Returns u1 +(sqrti 0) ;; Returns 0 +``` + +### log2 + +#### input: `int | uint` + +#### output: `int | uint` + +#### signature: `(log2 n)` + +#### description: + +Returns the _integer part_ of the power to which the number 2 must be raised to obtain the value `n`. Fails on zero or a negative number. + +#### example: + +```clarity +(log2 u8) ;; Returns u3 +(log2 8) ;; Returns 3 +(log2 u1) ;; Returns u0 +(log2 1000) ;; Returns 9 +``` + +### xor + +#### input: `int, int | uint, uint` + +#### output: `int | uint` + +#### signature: `(xor i1 i2)` + +#### description: + +Returns the result of bitwise exclusive or'ing `i1` with `i2`. + +#### example: + +```clarity +(xor 1 2) ;; Returns 3 +(xor 120 280) ;; Returns 352 +``` + +### and + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(and b1 b2 ...)` + +#### description: + +Returns `true` if all boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `false`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(and true false) ;; Returns false +(and (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns false +(and (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### or + +#### input: `bool, ...` + +#### output: `bool` + +#### signature: `(or b1 b2 ...)` + +#### description: + +Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Returns `true` if any boolean inputs are `true`. Importantly, the supplied arguments are evaluated in-order and lazily. Lazy evaluation means that if one of the arguments returns `true`, the function short-circuits, and no subsequent arguments are evaluated. + +#### example: + +```clarity +(or true false) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 4 4)) ;; Returns true +(or (is-eq (+ 1 2) 1) (is-eq 3 4)) ;; Returns false +(or (is-eq (+ 1 2) 3) (is-eq 4 4)) ;; Returns true +``` + +### not + +#### input: `bool` + +#### output: `bool` + +#### signature: `(not b1)` + +#### description: + +Returns the inverse of the boolean input. + +#### example: + +```clarity +(not true) ;; Returns false +(not (is-eq 1 2)) ;; Returns true +``` + +### is-eq + +#### input: `A, A, ...` + +#### output: `bool` + +#### signature: `(is-eq v1 v2...)` + +#### description: + +Compares the inputted values, returning `true` if they are all equal. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. Note that _unlike_ the `(and ...)` function, `(is-eq ...)` will _not_ short-circuit. All values supplied to is-eq _must_ be the same type. + +#### example: + +```clarity +(is-eq 1 1) ;; Returns true +(is-eq true false) ;; Returns false +(is-eq \"abc\" 234 234) ;; Throws type error +``` + +### if + +#### input: `bool, A, A` + +#### output: `A` + +#### signature: `(if bool1 expr1 expr2)` + +#### description: + +The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. The `if` function admits a boolean argument and two expressions which must return the same type. In the case that the boolean input is `true`, the `if` function evaluates and returns `expr1`. If the boolean input is `false`, the `if` function evaluates and returns `expr2`. + +#### example: + +```clarity +(if true 1 2) ;; Returns 1 +(if (> 1 2) 1 2) ;; Returns 2 +``` + +### let + +#### input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` + +#### output: `A` + +#### signature: `(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last)` + +#### description: + +The `let` function accepts a list of `variable name` and `expression` pairs, evaluating each expression and _binding_ it to the corresponding variable name. `let` bindings are sequential: when a `let` binding is evaluated, it may refer to prior binding. The _context_ created by this set of bindings is used for evaluating its body expressions. The let expression returns the value of the last such body expression. Note: intermediary statements returning a response type must be checked` + +#### example: + +```clarity +(let ((a 2) (b (+ 5 6 7))) (print a) (print b) (+ a b)) ;; Returns 20 +(let ((a 5) (c (+ a 1)) (d (+ c 1)) (b (+ a c d))) (print a) (print b) (+ a b)) ;; Returns 23 +``` + +### map + +#### input: `Function(A, B, ..., N) -> X, sequence_A, sequence_B, ..., sequence_N` + +#### output: `(list X)` + +#### signature: `(map func sequence_A sequence_B ... sequence_N)` + +#### description: + +The `map` function applies the function `func` to each corresponding element of the input sequences, and outputs a _list_ of the same type containing the outputs from those function applications. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. Also, note that, no matter what kind of sequences the inputs are, the output is always a list. + +#### example: + +```clarity +(map not (list true false true false)) ;; Returns (false true false true) +(map + (list 1 2 3) (list 1 2 3) (list 1 2 3)) ;; Returns (3 6 9) +(define-private (a-or-b (char (string-utf8 1))) (if (is-eq char u\"a\") u\"a\" u\"b\")) +(map a-or-b u\"aca\") ;; Returns (u\"a\" u\"b\" u\"a\") +(define-private (zero-or-one (char (buff 1))) (if (is-eq char 0x00) 0x00 0x01)) +(map zero-or-one 0x000102) ;; Returns (0x00 0x01 0x01) +``` + +### fold + +#### input: `Function(A, B) -> B, sequence_A, B` + +#### output: `B` + +#### signature: `(fold func sequence_A initial_B)` + +#### description: + +The `fold` function condenses `sequence_A` into a value of type `B` by recursively applies the function `func` to each element of the input sequence _and_ the output of a previous application of `func`. + +`fold` uses `initial_B` in the initial application of `func`, along with the first element of `sequence_A`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. The resulting value of type `B` is used for the next application of `func`, along with the next element of `sequence_A` and so on. `fold` returns the last value of type `B` returned by these successive applications `func`. + +Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. + +#### example: + +```clarity +(fold * (list 2 2 2) 1) ;; Returns 8 +(fold * (list 2 2 2) 0) ;; Returns 0 +;; calculates (- 11 (- 7 (- 3 2))) +(fold - (list 3 7 11) 2) ;; Returns 5 +(define-private (concat-string (a (string-ascii 20)) (b (string-ascii 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-string \"cdef\" \"ab\") ;; Returns \"fedcab\" +(fold concat-string (list \"cd\" \"ef\") \"ab\") ;; Returns \"efcdab\" +(define-private (concat-buff (a (buff 20)) (b (buff 20))) (unwrap-panic (as-max-len? (concat a b) u20))) +(fold concat-buff 0x03040506 0x0102) ;; Returns 0x060504030102 +``` + +### append + +#### input: `list A, A` + +#### output: `list` + +#### signature: `(append (list 1 2 3 4) 5)` + +#### description: + +The `append` function takes a list and another value with the same entry type, and outputs a list of the same type with max_len += 1. + +#### example: + +```clarity +(append (list 1 2 3 4) 5) ;; Returns (1 2 3 4 5) +``` + +### concat + +#### input: `sequence_A, sequence_A` + +#### output: `sequence_A` + +#### signature: `(concat sequence1 sequence2)` + +#### description: + +The `concat` function takes two sequences of the same type, and returns a concatenated sequence of the same type, with the resulting sequence_len = sequence1_len + sequence2_len. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. + +#### example: + +```clarity +(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4) +(concat \"hello \" \"world\") ;; Returns \"hello world\" +(concat 0x0102 0x0304) ;; Returns 0x01020304 +``` + +### as-max-len? + +#### input: `sequence_A, uint` + +#### output: `sequence_A` + +#### signature: `(as-max-len? sequence max_length)` sequence max_length)
+ +#### description: + +The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(as-max-len? (as-max-len? (list 2 2 2) u3) ;; Returns (some (2 2 2)) +(as-max-len? (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) (list 1 2 3) u2) ;; Returns none +(as-max-len? \"hello\" u10) ;; Returns (some \"hello\") +(as-max-len? 0x010203 u10) ;; Returns (some 0x010203) +``` + +### len + +#### input: `sequence_A` + +#### output: `uint` + +#### signature: `(len sequence)` + +#### description: + +The `len` function returns the length of a given sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` + +#### example: + +```clarity +(len \"blockstack\") ;; Returns u10 +(len (list 1 2 3 4 5)) ;; Returns u5 +(len 0x010203) ;; Returns u3 +``` + +### element-at + +#### input: `sequence_A, uint` + +#### output: `(optional A)` + +#### signature: `(element-at sequence index)` + +#### description: + +The `element-at` function returns the element at `index` in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. ` Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` ` + +#### example: + +```clarity +(element-at \"blockstack\" u5) ;; Returns (some \"s\") +(element-at (list 1 2 3 4 5) u5) ;; Returns none +(element-at (list 1 2 3 4 5) (+ u1 u2)) ;; Returns (some 4) +(element-at \"abcd\" u1) ;; Returns (some \"b\") +(element-at 0xfb01 u1) ;; Returns (some 0x01) +``` + +### index-of + +#### input: `sequence_A, A` + +#### output: `(optional uint)` + +#### signature: `(index-of sequence item)` + +#### description: + +The `index-of` function returns the first index at which `item` can be found, using `is-eq` checks, in the provided sequence. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. ` Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. If the target item is not found in the sequence (or if an empty string or buffer is supplied), this function returns `none`. + +#### example: + +```clarity +(index-of \"blockstack\" \"b\") ;; Returns (some u0) +(index-of \"blockstack\" \"k\") ;; Returns (some u4) +(index-of \"blockstack\" \"\") ;; Returns none +(index-of (list 1 2 3 4 5) 6) ;; Returns none +(index-of 0xfb01 0x01) ;; Returns (some u1) +``` + +### list + +#### input: `A, ...` + +#### output: `(list A)` + +#### signature: `(list expr1 expr2 expr3 ...)` + +#### description: + +The `list` function constructs a list composed of the inputted values. Each supplied value must be of the same type. Each supplied value must be of the same type. + +#### example: + +```clarity +(list (+ 1 2) 4 5) ;; Returns (3 4 5) +``` + +### var-get + +#### input: `VarName` + +#### output: `A` + +#### signature: `(var-get var-name)` + +#### description: + +The `var-get` function looks up and returns an entry from a contract's data map. The value is looked up using `var-name`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +``` + +### var-set + +#### input: `VarName, AnyType` + +#### output: `bool` + +#### signature: `(var-set var-name expr1)` + +#### description: + +The `var-set` function sets the value associated with the input variable to the inputted value. The function always returns `true`. + +#### example: + +```clarity +(define-data-var cursor int 6) +(var-get cursor) ;; Returns 6 +(var-set cursor (+ (var-get cursor) 1)) ;; Returns true +(var-get cursor) ;; Returns 7 +``` + +### map-get? + +#### input: `MapName, tuple` + +#### output: `(optional (tuple))` + +#### signature: `(map-get? map-name key-tuple)` + +#### description: + +The `map-get?` function looks up and returns an entry from a contract's data map. The value is looked up using `key-tuple`. If there is no value associated with that key in the data map, the function returns a `none` option. Otherwise, it returns `(some value)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(map-get? names-map (tuple (name \"blockstack\"))) ;; Returns (some (tuple (id 1337))) +(map-get? names-map { name: \"blockstack\" }) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-set + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-set map-name key-tuple value-tuple)` + +#### description: + +The `map-set` function sets the value associated with the input key to the inputted value. The `map-set` function sets the value associated with the input key to the inputted value. This function performs a _blind_ update; whether or not a value is already associated with the key, the function overwrites that existing association. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-set names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-insert + +#### input: `MapName, tuple_A, tuple_B` + +#### output: `bool` + +#### signature: `(map-insert map-name key-tuple value-tuple)` + +#### description: + +The `map-insert` function sets the value associated with the input key to the inputted value if and only if there is not already a value associated with the key in the map. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. If an insert occurs, the function returns `true`. If a value already existed for this key in the data map, the function returns `false`. + +Note: the `value-tuple` requires 1 additional byte for storage in the materialized blockchain state, and therefore the maximum size of a value that may be inserted into a map is MAX_CLARITY_VALUE - 1. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns false +(map-insert names-map (tuple (name \"blockstack\")) (tuple (id 1337))) ;; Same command, using a shorthand for constructing the tuple +``` + +### map-delete + +#### input: `MapName, tuple` + +#### output: `bool` + +#### signature: `(map-delete map-name key-tuple)` + +#### description: + +The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. The `map-delete` function removes the value associated with the input key for the given map. If an item exists and is removed, the function returns `true`. If a value did not exist for this key in the data map, the function returns `false`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 10) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns true +(map-delete names-map { name: \"blockstack\" }) ;; Returns false +(map-delete names-map (tuple (name \"blockstack\"))) ;; Same command, using a shorthand for constructing the tuple +``` + +### tuple + +#### input: `(key-name A), (key-name-2 B), ...` + +#### output: `(tuple (key-name A) (key-name-2 B) ...)` + +#### signature: `(tuple (key0 expr0) (key1 expr1) ...)` + +#### description: + +The `tuple` special form constructs a typed tuple from the supplied key and expression pairs. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. A `get` function can use typed tuples as input to select specific values from a given tuple. Key names may not appear multiple times in the same tuple definition. Supplied expressions are evaluated and associated with the expressions' paired key name. + +There is a shorthand using curly brackets of the form {key0: expr0, key1: expr, ...}` + +#### example: + +```clarity +(tuple (name \"blockstack\") (id 1337)) ;; using tuple +{name: \"blockstack\", id: 1337} ;; using curly brackets +``` + +### get + +#### input: `KeyName, (tuple) | (optional (tuple))` + +#### output: `A` + +#### signature: `(get key-name tuple)` + +#### description: + +The `get` function fetches the value associated with a given key from the supplied typed tuple. If an `Optional` value is supplied as the inputted tuple, `get` returns an `Optional` type of the specified key in the tuple. If the supplied option is a `(none)` option, get returns `(none)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-insert names-map { name: \"blockstack\" } { id: 1337 }) ;; Returns true +(get id (tuple (name \"blockstack\") (id 1337))) ;; Returns 1337 +(get id (map-get? names-map (tuple (name \"blockstack\")))) ;; Returns (some 1337) +(get id (map-get? names-map (tuple (name \"non-existent\")))) ;; Returns none +``` + +### merge + +#### input: `tuple, tuple` + +#### output: `tuple` + +#### signature: `(merge tuple { key1: val1 })` + +#### description: + +The `merge` function returns a new tuple with the combined fields, without mutating the supplied tuples. + +#### example: + +```clarity +(define-map users { id: int } { name: (string-ascii 12), address: (optional principal) }) +(map-insert users { id: 1337 } { name: \"john\", address: none }) ;; Returns true +(let ((user (unwrap-panic (map-get? users { id: 1337 })))) +(merge user { address: (some 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) })) ;; Returns (tuple (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)) (name \"john\")) +``` + +### begin + +#### input: `AnyType, ... A` + +#### output: `A` + +#### signature: `(begin expr1 expr2 expr3 ... expr-last)` + +#### description: + +The `begin` function evaluates each of its input expressions, returning the return value of the last such expression. Note: intermediary statements returning a response type must be checked. + +#### example: + +```clarity +(begin (+ 1 2) 4 5) ;; Returns 5 +``` + +### hash160 + +#### input: `buff|uint|int` + +#### output: `(buff 20)` + +#### signature: `(hash160 value)` + +#### description: + +The `hash160` function computes `RIPEMD160(SHA256(x))` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(hash160 0) ;; Returns 0xe4352f72356db555721651aa612e00379167b30f +``` + +### sha256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha256 value)` + +#### description: + +The `sha256` function computes `SHA256(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha256 0) ;; Returns 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb +``` + +### sha512 + +#### input: `buff|uint|int` + +#### output: `(buff 64)` + +#### signature: `(sha512 value)` + +#### description: + +The `sha512` function computes `SHA512(x)` of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512 1) ;; Returns 0x6fcee9a7b7a7b821d241c03c82377928bc6882e7a08c78a4221199bfa220cdc55212273018ee613317c8293bb8d1ce08d1e017508e94e06ab85a734c99c7cc34 +``` + +### sha512/256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(sha512/256 value)` + +#### description: + +The `sha512/256` function computes `SHA512/256(x)` (the SHA512 algorithm with the 512/256 initialization vector, truncated to 256 bits) of the inputted value. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(sha512/256 1) ;; Returns 0x515a7e92e7c60522db968d81ff70b80818fc17aeabbec36baf0dda2812e94a86 +``` + +### keccak256 + +#### input: `buff|uint|int` + +#### output: `(buff 32)` + +#### signature: `(keccak256 value)` + +#### description: + +The `keccak256` function computes `KECCAK256(value)` of the inputted value. Note that this differs from the `NIST SHA-3` (that is, FIPS 202) standard. If an integer (128 bit) is supplied the hash is computed over the little-endian representation of the integer. + +#### example: + +```clarity +(keccak256 0) ;; Returns 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4 +``` + +### secp256k1-recover? + +#### input: `(buff 32), (buff 65)` + +#### output: `(response (buff 33) uint)` + +#### signature: `(secp256k1-recover? message-hash signature)` + +#### description: + +The `secp256k1-recover?` function recovers the public key used to sign the message which sha256 is `message-hash` with the provided `signature`. If the signature does not match, it will return the error code `(err u1).`. If the signature is invalid, it will return the error code `(err u2).`. The signature includes 64 bytes plus an additional recovery id (00..03) for a total of 65 bytes. + +#### example: + +```clarity +(secp256k1-recover? 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) + ;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) +``` + +### secp256k1-verify + +#### input: `(buff 32), (buff 64) | (buff 65), (buff 33)` + +#### output: `bool` + +#### signature: `(secp256k1-verify message-hash signature public-key)` + +#### description: + +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. + +#### example: + +```clarity +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 + 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a13 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns true +(secp256k1-verify 0x0000000000000000000000000000000000000000000000000000000000000000 + 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns false +``` + +### print + +#### input: `A` + +#### output: `A` + +#### signature: `(print expr)` + +#### description: + +The `print` function evaluates and returns its input expression. On Stacks Core nodes configured for development (as opposed to production mining nodes), this function prints the resulting value to `STDOUT` (standard output). + +#### example: + +```clarity +(print (+ 1 2 3)) ;; Returns 6 +``` + +### contract-call? + +#### input: `ContractName, PublicFunctionName, Arg0, ...` + +#### output: `(response A B)` + +#### signature: `(contract-call? .contract-name function-name arg0 arg1 ...)` + +#### description: + +The `contract-call?` function executes the given public function of the given contract. You _may not_ use this function to call a public function defined in the current contract. If the public function returns _err_, any database changes resulting from calling `contract-call?` are aborted. If the function returns _ok_, database changes occurred. + +#### example: + +```clarity + +;; instantiate the sample-contracts/tokens.clar contract first! +(as-contract (contract-call? .tokens mint! u19)) ;; Returns (ok u19) +``` + +### as-contract + +#### input: `A` + +#### output: `A` + +#### signature: `(as-contract expr)` + +#### description: + +The `as-contract` function switches the current context's `tx-sender` value to the _contract's_ principal and executes `expr` with that context. It returns the resulting value of `expr`. + +#### example: + +```clarity +(as-contract tx-sender) ;; Returns S1G2081040G2081040G2081040G208105NK8PE5.docs-test +``` + +### contract-of + +#### input: `Trait` + +#### output: `principal` + +#### signature: `(contract-of .contract-name)` + +#### description: + +The `contract-of` function returns the principal of the contract implementing the trait. + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok (contract-of contract)))) ;; returns the principal of the contract implementing +``` + +### principal-of? + +#### input: `(buff 33)` + +#### output: `(response principal uint)` + +#### signature: `(principal-of? public-key)` public-key)
+ +#### description: + +The `principal-of?` function returns the principal derived from the provided public key. The `principal-of?` function returns the principal derived from the provided public key. If the `public-key` is invalid, it will return the error code `(err u1).`. ` ` + +#### example: + +```clarity +(principal-of? 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) ;; Returns (ok ST1AW6EKPGT61SQ9FNVDS17RKNWT8ZP582VF9HSCP) +``` + +### at-block + +#### input: `(buff 32), A` + +#### output: `A` + +#### signature: `(at-block id-block-hash expr)` + +#### description: + +The `at-block` function evaluates the expression `expr` _as if_ it were evaluated at the end of the block indicated by the _block-hash_ argument. The `expr` closure must be read-only. + +Note: The block identifying hash must be a hash returned by the `id-header-hash` block information property. This hash uniquely identifies Stacks blocks and is unique across Stacks forks. While the hash returned by `header-hash` is unique within the context of a single fork, it is not unique across Stacks forks. + +The function returns the result of evaluating `expr`. + +#### example: + +```clarity +(define-data-var data int 1) +(at-block 0x0000000000000000000000000000000000000000000000000000000000000000 block-height) ;; Returns u0 +(at-block (get-block-info? id-header-hash 0) (var-get data)) ;; Throws NoSuchDataVariable because `data` wasn't initialized at block height 0 +``` + +### get-block-info? + +#### input: `BlockInfoPropertyName, BlockHeightInt` + +#### output: `(optional buff) | (optional uint)` + +#### signature: `(get-block-info? prop-name block-height-expr)` + +#### description: + +The `get-block-info?` function fetches data for a block of the given block height. The value and type returned are determined by the specified `BlockInfoPropertyName`. If the provided `BlockHeightInt` does not correspond to an existing block prior to the current block, the function returns `none`. The currently available property names are `time`, `header-hash`, `burnchain-header-hash`, `id-header-hash`, `miner-address`, and `vrf-seed`. + +The `time` property returns an integer value of the block header time field. This is a Unix epoch timestamp in seconds which roughly corresponds to when the block was mined. **Warning**: this does not increase monotonically with each block and block times are accurate only to within two hours. See [BIP113](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki) for more information. + +The `header-hash`, `burnchain-header-hash`, `id-header-hash`, and `vrf-seed` properties return a 32-byte buffer. + +The `miner-address` property returns a `principal` corresponding to the miner of the given block. + +The `id-header-hash` is the block identifier value that must be used as input to the `at-block` function. + +#### example: + +```clarity +(get-block-info? time u0) ;; Returns (some u1557860301) +(get-block-info? header-hash u0) ;; Returns (some 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) +(get-block-info? vrf-seed u0) ;; Returns (some 0xf490de2920c8a35fabeb13208852aa28c76f9be9b03a4dd2b3c075f7a26923b4) +``` + +### err + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(err value)` + +#### description: + +The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. The `err` function constructs a response type from the input value. Use `err` for creating return values in public functions. An _err_ value indicates that any database changes during the processing of the function should be rolled back. + +#### example: + +```clarity +(err true) ;; Returns (err true) +``` + +### ok + +#### input: `A` + +#### output: `(response A B)` + +#### signature: `(ok value)` + +#### description: + +The `ok` function constructs a response type from the input value. Use `ok` for creating return values in public functions. An _ok_ value indicates that any database changes during the processing of the function should materialize. + +#### example: + +```clarity +(ok 1) ;; Returns (ok 1) +``` + +### some + +#### input: `A` + +#### output: `(optional A)` + +#### signature: `(some value)` + +#### description: + +The `some` function constructs a `optional` type from the input value. + +#### example: + +```clarity +(some 1) ;; Returns (some 1) +(is-none (some 2)) ;; Returns false +``` + +### default-to + +#### input: `A, (optional A)` + +#### output: `A` + +#### signature: `(default-to default-value option-value)` + +#### description: + +The `default-to` function attempts to 'unpack' the second argument: if the argument is a `(some ...)` option, it returns the inner value of the option. If the second argument is a `(none)` value, `default-to` it returns the value of `default-value`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(default-to 0 (get id (map-get? names-map (tuple (name \"blockstack\"))))) ;; Returns 1337 +(default-to 0 (get id (map-get? names-map (tuple (name \"non-existent\"))))) ;; Returns 0 +``` + +### asserts! + +#### input: `bool, C` + +#### output: `bool` + +#### signature: `(asserts! signature: (asserts! bool-expr thrown-value)` + +#### description: + +The `asserts!` function admits a boolean argument and asserts its evaluation: if bool-expr is `true`, `asserts!` returns `true` and proceeds in the program execution. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. If the supplied argument is returning a false value, `asserts!` _returns_ `thrown-value` and exits the current control-flow. + +#### example: + +```clarity +(asserts! (is-eq 1 1) (err 1)) ;; Returns true +``` + +### unwrap! + +#### input: `(optional A) | (response A B), C` + +#### output: `A` + +#### signature: `(unwrap! option-input thrown-value)` + +#### description: + +The `unwrap!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `unwrap!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `unwrap!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(define-private (get-name-or-err (name (string-ascii 12))) + (let ((raw-name (unwrap! (map-get? names-map { name: name }) (err 1)))) + (ok raw-name))) + +(get-name-or-err \"blockstack\") ;; Returns (ok (tuple (id 1337))) +(get-name-or-err \"non-existent\") ;; Returns (err 1) +``` + +### unwrap-err! + +#### input: `(response A B), C` + +#### output: `B` + +#### signature: `(unwrap-err! response-input thrown-value)` + +#### description: + +The `unwrap-err!` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap-err!` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err!` _returns_ `thrown-value` from the current function and exits the current control-flow. + +#### example: + +```clarity +(unwrap-err! (err 1) false) ;; Returns 1 +``` + +### unwrap-panic + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(unwrap-panic option-input)` + +#### description: + +The `unwrap` function attempts to 'unpack' its argument: if the argument is an option type, and the argument is a `(some ...)` option, this function returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, it returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `(none)` value, `unwrap` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(unwrap-panic (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(unwrap-panic (map-get? names-map { name: \"non-existent\" })) ;; Throws a runtime exception +``` + +### unwrap-err-panic + +#### input: `(response A B)` + +#### output: `B` + +#### signature: `(unwrap-err-panic response-input)` + +#### description: + +The `unwrap-err` function attempts to 'unpack' the first argument: if the argument is an `(err ...)` response, `unwrap` returns the inner value of the `err`. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. If the supplied argument is an `(ok ...)` value, `unwrap-err` throws a runtime error, aborting any further processing of the current transaction. + +#### example: + +```clarity +(unwrap-err-panic (err 1)) ;; Returns 1 +(unwrap-err-panic (ok 1)) ;; Throws a runtime exception +``` + +### match + +#### input: `(optional A) name expression expression | (response A B) name expression name expression` + +#### output: `C` + +#### signature: `(match opt-input some-binding-name some-branch none-branch) | + +(match-resp input ok-binding-name ok-branch err-binding-name err-branch)` + +#### description: + +The `match` function is used to test and destructure optional and response types. + +If the `input` is an optional, it tests whether the provided `input` is a `some` or `none` option, and evaluates `some-branch` or `none-branch` in each respective case. + +Within the `some-branch`, the _contained value_ of the `input` argument is bound to the provided `some-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +If the `input` is a response, it tests whether the provided `input` is an `ok` or `err` response type, and evaluates `ok-branch` or `err-branch` in each respective case. + +Within the `ok-branch`, the _contained ok value_ of the `input` argument is bound to the provided `ok-binding-name` name. + +Within the `err-branch`, the _contained err value_ of the `input` argument is bound to the provided `err-binding-name` name. + +Only _one_ of the branches will be evaluated (similar to `if` statements). + +Note: Type checking requires that the type of both the ok and err parts of the response object be determinable. For situations in which one of the parts of a response is untyped, you should use `unwrap-panic` or `unwrap-err-panic` instead of `match`. + +#### example: + +```clarity + +(define-private (add-10 (x (optional int))) + (match x + value (+ 10 value) + 10)) +(add-10 (some 5)) ;; Returns 15 +(add-10 none) ;; Returns 10 + +(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) + (match x + value (ok (+ to-add value)) + err-value (err err-value))) +(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) +(add-or-pass-err (err \"ERROR\") 20) ;; Returns (err \"ERROR\") +``` + +### try! + +#### input: `(optional A) | (response A B)` + +#### output: `A` + +#### signature: `(try! signature: (try! option-input)` + +#### description: + +The `try!` function attempts to 'unpack' the first argument: if the argument is an option type, and the argument is a `(some ...)` option, `try!` returns the inner value of the option. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. If the argument is a response type, and the argument is an `(ok ...)` response, `try!` returns the inner value of the `ok`. If the supplied argument is either an `(err ...)` or a `none` value, `try!` _returns_ either `none` or the `(err ...)` value from the current function and exits the current control-flow. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(try! (map-get? names-map { name: \"blockstack\" })) ;; Returns (tuple (id 1337)) +(define-private (checked-even (x int)) + (if (is-eq (mod x 2) 0) + (ok x) + (err false))) +(define-private (double-if-even (x int)) + (ok (* 2 (try! (checked-even x))))) +(double-if-even 10) ;; Returns (ok 20) +(double-if-even 3) ;; Returns (err false) +``` + +### is-ok + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-ok value)` + +#### description: + +`is-ok` tests a supplied response value, returning `true` if the response was `ok`, and `false` if it was an `err`. + +#### example: + +```clarity +(is-ok (ok 1)) ;; Returns true +(is-ok (err 1)) ;; Returns false +``` + +### is-none + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-none value)` + +#### description: + +`is-none` tests a supplied option value, returning `true` if the option value is `(none)`, and `false` if it is a `(some ...)`. + +#### example: + +```clarity +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-none (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns false +(is-none (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns true +``` + +### is-err + +#### input: `(response A B)` + +#### output: `bool` + +#### signature: `(is-err value)` + +#### description: + +`is-err` tests a supplied response value, returning `true` if the response was an `err`, and `false` if it was an `ok`. + +#### example: + +```clarity +(is-err (ok 1)) ;; Returns false +(is-err (err 1)) ;; Returns true +``` + +### is-some + +#### input: `(optional A)` + +#### output: `bool` + +#### signature: `(is-some value)` + +#### description: + +`is-some` tests a supplied option value, returning `true` if the option value is `(some ...)`, and `false` if it is a `none`. + +#### example: + +```clarity + +(define-map names-map { name: (string-ascii 12) } { id: int }) +(map-set names-map { name: \"blockstack\" } { id: 1337 }) +(is-some (get id (map-get? names-map { name: \"blockstack\" }))) ;; Returns true +(is-some (get id (map-get? names-map { name: \"non-existent\" }))) ;; Returns false +``` + +### filter + +#### input: `Function(A) -> bool, sequence_A` + +#### output: `sequence_A` + +#### signature: `(filter func sequence)` + +#### description: + +The `filter` function applies the input function `func` to each element of the input sequence, and returns the same sequence with any elements removed for which `func` returned `false`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`, for which the corresponding element types are, respectively, `A`, `(buff 1)`, `(string-ascii 1)` and `(string-utf8 1)`. The `func` argument must be a literal function name. ` + +#### example: + +```clarity + +(filter not (list true false true false)) ;; Returns (false false) +(define-private (is-a (char (string-utf8 1))) (is-eq char u\"a\")) +(filter is-a u\"acabd\") ;; Returns u\"aa\" +(define-private (is-zero (char (buff 1))) (is-eq char 0x00)) +(filter is-zero 0x00010002) ;; Returns 0x0000 +``` + +### ft-get-balance + +#### input: `TokenName, principal` + +#### output: `uint` + +#### signature: `(ft-get-balance token-name principal)` + +#### description: + +`ft-get-balance` returns `token-name` balance of the principal `principal`. The token type must have been defined using `define-fungible-token`. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-balance stackaroo 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u100 +``` + +### nft-get-owner? + +#### input: `AssetName, A` + +#### output: `(optional principal)` + +#### signature: `(nft-get-owner? asset-class asset-identifier)` asset-class asset-identifier) + +#### description: + +`nft-get-owner?` returns the owner of an asset, identified by `asset-identifier`, or `none` if the asset does not exist. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. The asset type must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Roo\") ;; Returns (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) +(nft-get-owner? stackaroo \"Too\") ;; Returns none +``` + +### ft-transfer? + +#### input: `TokenName, uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-transfer? signature: (ft-transfer? token-name amount sender recipient)` + +#### description: + +`ft-transfer?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token` by debiting the `sender` principal. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. In contrast to `stx-transfer?`, any user can transfer the assets. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-transfer? stackaroo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-transfer? stackaroo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +``` + +### nft-transfer? + +#### input: `AssetName, A, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-transfer? signature: (nft-transfer? asset-class asset-identifier sender recipient)` + +#### description: + +`nft-transfer?` is used to change the owner of an asset identified by `asset-identifier` from `sender` to `recipient`. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. The `asset-class` must have been defined by `define-non-fungible-token` and `asset-identifier` must be of the type specified in that definition. In contrast to `stx-transfer?`, any user can transfer the asset. When used, relevant guards need to be added. + +This function returns (ok true) if the transfer is successful. This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not own the asset `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- asset identified by asset-identifier does not exist ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-transfer? stackaroo \"Roo\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) +(nft-transfer? stackaroo \"Stacks\" 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u3) +``` + +### nft-mint? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-mint? asset-class asset-identifier recipient)` + +#### description: + +`nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _already exists_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-mint? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-mint? token-name amount recipient)` token-name amount recipient) + +#### description: + +`ft-mint?` is used to increase the token balance for the `recipient` principal for a token type defined using `define-fungible-token`. The increased token balance is _not_ transfered from another principal, but rather minted. The increased token balance is _not_ transferred from another principal, but rather minted. + +If a non-positive amount is provided to mint, this function returns `(err 1)`. Otherwise, on successfuly mint, it returns `(ok true)`. ` Otherwise, on successfully mint, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### ft-get-supply + +#### input: `TokenName` + +#### output: `uint` + +#### signature: `(ft-get-supply token-name)` + +#### description: + +`ft-get-balance` returns `token-name` circulating supply. `ft-get-balance` returns `token-name` circulating supply. The token type must have been defined using `define-fungible-token`. + +#### example: + +```clarity +(define-fungible-token stackaroo) +(ft-mint? (define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) +(ft-get-supply stackaroo) ;; Returns u100 +``` + +### ft-burn? + +#### input: `TokenName, uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(ft-burn? token-name amount sender)` token-name amount sender) + +#### description: + +`ft-burn?` is used to decrease the token balance for the `sender` principal for a token type defined using `define-fungible-token`. The decreased token balance is _not_ transfered to another principal, but rather destroyed, reducing the circulating supply. The decreased token balance is _not_ transferred to another principal, but rather destroyed, reducing the circulating supply. + +If a non-positive amount is provided to burn, this function returns `(err 1)`. Otherwise, on successfuly burn, it returns `(ok true)`. ` Otherwise, on successfully burn, it returns `(ok true)`. + +#### example: + +```clarity + +(define-fungible-token stackaroo) +(ft-mint? (define-fungible-token stackaroo) +(ft-mint? stackaroo u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-burn? stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) stackaroo u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### nft-burn? + +#### input: `AssetName, A, principal` + +#### output: `(response bool uint)` + +#### signature: `(nft-burn? signature: (nft-burn? asset-class asset-identifier recipient)` + +#### description: + +`nft-burn?` is used to burn an asset and remove that asset's owner from the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. `nft-mint?` is used to instantiate an asset and set that asset's owner to the `recipient` principal. The asset must have been defined using `define-non-fungible-token`, and the supplied `asset-identifier` must be of the same type specified in that definition. + +If an asset identified by `asset-identifier` _doesn't exist_, this function will return an error with the following error code: + +`(err u1)` + +Otherwise, on successfully burn, it returns `(ok true)`. ` + +#### example: + +```clarity +(define-non-fungible-token stackaroo (string-ascii 40)) +(nft-mint? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(nft-burn? stackaroo \"Roo\" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +``` + +### stx-get-balance + +#### input: `principal` + +#### output: `uint` + +#### signature: `(stx-get-balance owner)` + +#### description: + +`stx-get-balance` is used to query the STX balance of the `owner` principal. + +This function returns the STX balance of the `owner` principal. In the event that the `owner` principal isn't materialized, it returns 0. ` In the event that the `owner` principal isn't materialized, it returns 0. + +#### example: + +```clarity +(stx-get-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns u0 +(stx-get-balance (as-contract tx-sender)) ;; Returns u1000 +``` + +### stx-transfer? + +#### input: `uint, principal, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-transfer? amount sender recipient)` amount sender recipient) + +#### description: + +`stx-transfer?` is used to increase the STX balance for the `recipient` principal by debiting the `sender` principal. The `sender` principal _must_ be equal to the current context's `tx-sender`. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u2)` -- `sender` and `recipient` are the same principal `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity + +(as-contract + (stx-transfer? (as-contract + (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (ok true) +(as-contract + (stx-transfer? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR tx-sender)) ;; Returns (err u4) +``` + +### stx-burn? + +#### input: `uint, principal` + +#### output: `(response bool uint)` + +#### signature: `(stx-burn? amount sender)` amount sender) + +#### description: + +`stx-burn?` debits the `sender` principal's STX holdings by `amount`, destroying the STX. The `sender` principal _must_ be equal to the current context's `tx-sender`. The `sender` principal _must_ be equal to the current context's `tx-sender`. + +This function returns (ok true) if the transfer is successful. This function returns (ok true) if the transfer is successful. In the event of an unsuccessful transfer it returns one of the following error codes: + +`(err u1)` -- `sender` does not have enough balance to transfer `(err u3)` -- amount to send is non-positive `(err u4)` -- the `sender` principal is not the current `tx-sender` + +#### example: + +```clarity +(as-contract + (stx-burn? (as-contract + (stx-burn? u60 tx-sender)) ;; Returns (ok true) +(as-contract + (stx-burn? u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)) ;; Returns (err u4) +``` + +### define-constant + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-constant name expression)` + +#### description: + +`define-constant` is used to define a private constant value in a smart contract. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. The expression passed into the definition is evaluated at contract launch, in the order that it is supplied in the contract. This can lead to undefined function or undefined variable errors in the event that a function or variable used in the expression has not been defined before the constant. + +Like other kinds of definition statements, `define-constant` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity + +(define-constant four (+ 2 2)) +(+ 4 four) ;; Returns 8 +``` + +### define-private + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-private (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-private` is used to define _private_ functions for a smart contract. `define-private` is used to define _private_ functions for a smart contract. Private functions may not be called from other smart contracts, nor may they be invoked directly by users. Instead, these functions may only be invoked by other functions defined in the same smart contract. Instead, these functions may only be invoked by other functions defined in the same smart contract. + +Like other kinds of definition statements, `define-private` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Private functions may return any type. + +#### example: + +```clarity +(define-private (max-of (i1 int) (i2 int)) + (if (> i1 i2) + i1 + i2)) +(max-of 4 6) ;; Returns 6 +``` + +### define-public + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-public (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-public` is used to define a _public_ function and transaction for a smart contract. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. Public functions are callable from other smart contracts and may be invoked directly by users by submitting a transaction to the Stacks blockchain. + +Like other kinds of definition statements, `define-public` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Public functions _must_ return a ResponseType (using either `ok` or `err`). Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. Any datamap modifications performed by a public function is aborted if the function returns an `err` type. Public functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-public (hello-world (input int)) + (begin (print (+ 2 input)) + (ok input))) +``` + +### define-read-only + +#### input: `MethodSignature, MethodBody` + +#### output: `Not Applicable` + +#### signature: `(define-read-only (function-name (arg-name-0 arg-type-0) (arg-name-1 arg-type-1) ...) function-body)` + +#### description: + +`define-read-only` is used to define a _public read-only_ function for a smart contract. Such functions are callable from other smart contracts. Such functions are callable from other smart contracts. + +Like other kinds of definition statements, `define-read-only` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Read-only functions may return any type. Read-only functions may return any type. However, read-only functions may not perform any datamap modifications, or call any functions which perform such modifications. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. This is enforced both during type checks and during the execution of the function. Public read-only functions may be invoked by other contracts via `contract-call?`. + +#### example: + +```clarity +(define-read-only (just-return-one-hundred) + (* 10 10)) +``` + +### define-map + +#### input: `MapName, TypeDefinition, TypeDefinition` + +#### output: `Not Applicable` + +#### signature: `(define-map map-name key-type value-type)` + +#### description: + +`define-map` is used to define a new datamap for use in a smart contract. Such maps are only modifiable by the current smart contract. + +Maps are defined with a key type and value type, often these types are tuple types. + +Like other kinds of definition statements, `define-map` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-map squares { x: int } { square: int }) +(define-private (add-entry (x int)) + (map-insert squares { x: 2 } { square: (* x x) })) +(add-entry 1) +(add-entry 2) +(add-entry 3) +(add-entry 4) +(add-entry 5) +``` + +### define-data-var + +#### input: `VarName, TypeDefinition, Value` + +#### output: `Not Applicable` + +#### signature: `(define-data-var var-name type value)` + +#### description: + +`define-data-var` is used to define a new persisted variable for use in a smart contract. Such variable are only modifiable by the current smart contract. Such variable are only modifiable by the current smart contract. + +Persisted variable are defined with a type and a value. + +Like other kinds of definition statements, `define-data-var` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +#### example: + +```clarity +(define-data-var size int 0) +(define-private (set-size (value int)) + (var-set size value)) +(set-size 1) +(set-size 2) +``` + +### define-fungible-token + +#### input: `TokenName, ` + +#### output: `Not Applicable` + +#### signature: `(define-fungible-token token-name )` + +#### description: + +`define-fungible-token` is used to define a new fungible token class for use in the current contract. + +The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. The second argument, if supplied, defines the total supply of the fungible token. This ensures that all calls to the `ft-mint?` function will never be able to create more than `total-supply` tokens. If any such call were to increase the total supply of tokens passed that amount, that invocation of `ft-mint?` will result in a runtime error and abort. + +Like other kinds of definition statements, `define-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Tokens defined using `define-fungible-token` may be used in `ft-transfer?`, `ft-mint?`, and `ft-get-balance` functions` + +#### example: + +```clarity +(define-fungible-token stacks) +(define-fungible-token limited-supply-stacks u100) +``` + +### define-non-fungible-token + +#### input: `AssetName, TypeSignature` + +#### output: `Not Applicable` + +#### signature: `(define-non-fungible-token asset-name asset-identifier-type)` + +#### description: + +`define-non-fungible-token` is used to define a new non-fungible token class for use in the current contract. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. Individual assets are identified by their asset identifier, which must be of the type `asset-identifier-type`. Asset identifiers are _unique_ identifiers. + +Like other kinds of definition statements, `define-non-fungible-token` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). + +Assets defined using `define-non-fungible-token` may be used in `nft-transfer?`, `nft-mint?`, and `nft-get-owner?` functions` + +#### example: + +```clarity +(define-non-fungible-token names (buff 50)) +``` + +### define-trait + +#### input: `VarName, [MethodSignature]` + +#### output: `Not Applicable` + +#### signature: `(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type))))` + +#### description: + +`define-trait` is used to define a new trait definition for use in a smart contract. `define-trait` is used to define a new trait definition for use in a smart contract. Other contracts can implement a given trait and then have their contract identifier being passed as function arguments in order to be called dynamically with `contract-call?`. + +Traits are defined with a name, and a list functions defined with a name, a list of argument types, and return type. + +Like other kinds of definition statements, `define-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put a define statement in the middle of a function body). ` + +#### example: + +```clarity +(define-trait token-trait + ((transfer? (define-trait token-trait + ((transfer? (principal principal uint) (response uint uint)) + (get-balance (principal) (response uint uint)))) +``` + +### use-trait + +#### input: `VarName, TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(use-trait trait-alias trait-identifier)` + +#### description: + +`use-trait` is used to bring a trait, defined in another contract, to the current contract. Subsequent references to an imported trait are signaled with the syntax ``. Subsequent references to an imported trait are signaled with the syntax ``. + +Traits import are defined with a name, used as an alias, and a trait identifier. Traits import are defined with a name, used as an alias, and a trait identifier. Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `use-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). ` + +#### example: + +```clarity +(use-trait token-a-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) +(define-public (forward-get-balance (user principal) (contract )) + (begin + (ok 1))) +``` + +### impl-trait + +#### input: `TraitIdentifier` + +#### output: `Not Applicable` + +#### signature: `(impl-trait trait-identifier)` + +#### description: + +`impl-trait` can be use for asserting that a contract is fully implementing a given trait. `impl-trait` can be use for asserting that a contract is fully implementing a given trait. Additional checks are being performed when the contract is being published, rejecting the deployment if the contract is violating the trait specification. + +Trait identifiers can either be using the sugared syntax (.token-a.token-trait), or be fully qualified ('SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait). + +Like other kinds of definition statements, `impl-trait` may only be used at the top level of a smart contract definition (i.e., you cannot put such a statement in the middle of a function body). ` + +#### example: + +```clarity +(impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) " } (from principal) (to principal) (amount uint)) + (ok u0)) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-keywords.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-keywords.md new file mode 100644 index 0000000000..45608736a5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-keywords.md @@ -0,0 +1,146 @@ +--- +title: Keywords +description: See a detailed list of all keywords for the Clarity language. +sidebar_position: 4 +tags: + - clarity +--- + +![](/img/keywords.jpg) + +## Keyword reference + +Detailed list of all keywords for the Clarity language. + +### contract-caller + +#### output: `principal` + +#### description: + +Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. Returns the caller of the current contract context. If this contract is the first one called by a signed transaction, the caller will be equal to the signing principal. If `contract-call?` was used to invoke a function from a new contract, `contract-caller` changes to the _calling_ contract's principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. If `as-contract` is used to change the `tx-sender` context, `contract-caller` _also_ changes to the same contract principal. + +#### example: + +```clarity +(print contract-caller) ;; Will print out a Stacks address of the transaction sender +``` + +### tx-sender + +#### output: `principal` + +#### description: + +Returns the original sender of the current transaction, or if `as-contract` was called to modify the sending context, it returns that contract principal. + +#### example: + +```clarity +(print tx-sender) ;; Will print out a Stacks address of the transaction sender +``` + +### block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the Stacks blockchain as an uint + +#### example: + +```clarity +(> block-height 1000) ;; returns true if the current block-height has passed 1000 blocks. +``` + +### burn-block-height + +#### output: `uint` + +#### description: + +Returns the current block height of the underlying burn blockchain as a uint + +#### example: + +```clarity +(> burn-block-height 1000) ;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks. +``` + +### none + +#### output: `(optional ?)` + +#### description: + +Represents the _none_ option indicating no value for a given optional (analogous to a null value). + +#### example: + +```clarity +(define-public (only-if-positive (a int)) + (if (> a 0) + (some a) + none)) +(only-if-positive 4) ;; Returns (some 4) +(only-if-positive (- 3)) ;; Returns none +``` + +### true + +#### output: `bool` + +#### description: + +Boolean true constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### false + +#### output: `bool` + +#### description: + +Boolean false constant. + +#### example: + +```clarity +(and true false) ;; Evaluates to false +(or false true) ;; Evaluates to true +``` + +### stx-liquid-supply + +#### output: `uint` + +#### description: + +Returns the total number of micro-STX (uSTX) that are liquid in the system as of this block. + +#### example: + +```clarity +(print stx-liquid-supply) ;; Will print out the total number of liquid uSTX +``` + +### is-in-regtest + +#### output: `bool` + +#### description: + +Returns whether or not the code is running in a regression test + +#### example: + +```clarity +(print is-in-regtest) ;; Will print 'true' if the code is running in a regression test +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-types.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-types.md new file mode 100644 index 0000000000..3973afbaeb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/language-types.md @@ -0,0 +1,25 @@ +--- +title: Types +description: See a detailed list of all types for the Clarity language. +sidebar_position: 2 +tags: + - clarity +--- + +## Clarity Type System + +The type system contains the following types: + +| Types | Notes | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `int` | signed 128-bit integer | +| `uint` | unsigned 128-bit integer | +| `bool` | boolean value (`true` or `false`) | +| `principal` | object representing a principal (whether a contract principal or standard principal) | +| `(buff max-len)` | byte buffer of maximum length `max-len`. | +| `(string-ascii max-len)` | ASCII string of maximum length `max-len` | +| `(string-utf8 max-len)` | UTF-8 string of maximum length `max-len` (u"A smiley face emoji \u{1F600} as a utf8 string") | +| `(list max-len entry-type)` | list of maximum length `max-len`, with entries of type `entry-type` | +| `{label-0: value-type-0, label-1: value-type-1, ...}` | tuple, group of data values with named fields | +| `(optional some-type)` | an option type for objects that can either be `(some value)` or `none` | +| `(response ok-type err-type)` | object used by public functions to commit their changes or abort. object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior. | diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json new file mode 100644 index 0000000000..eb32d48e32 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Noteworthy Contracts", + "position": 5, + "link": { + "type": "generated-index", + "description": "Specific deployed Clarity Contracts worth mentioning." + } +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md new file mode 100644 index 0000000000..13a0198924 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/bns-contract.md @@ -0,0 +1,519 @@ +--- +title: BNS Contract +description: The Bitcoin Name System. +--- + +![](/img/satoshi-btc.png) + +## Introduction + +The Bitcoin Name System (BNS) is implemented as a smart contract using Clarity. + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### name-import + +#### Input: `(buff 20), (buff 48), principal, (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-import namespace name beneficiary zonefile-hash)` + +#### Description: + +Imports name to a revealed namespace. Each imported name is given both an owner and some off-chain state. + +### name-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(name-preorder hashed-salted-fqn stx-to-burn)` + +#### Description: + +Preorders a name by telling all BNS nodes the salted hash of the BNS name. It pays the registration fee to the namespace owner's designated address. + +### name-register + +#### Input: `(buff 20), (buff 48), (buff 20), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-register namespace name salt zonefile-hash)` + +#### Description: + +Reveals the salt and the name to all BNS nodes, and assigns the name an initial public key hash and zone file hash. + +### name-renewal + +#### Input: `(buff 20), (buff 48), uint, (optional principal), (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-renewal namespace name stx-to-burn new-owner zonefile-hash)` + +#### Description: + +Depending in the namespace rules, a name can expire. For example, names in the .id namespace expire after 2 years. You need to send a name renewal every so often to keep your name. + +You will pay the registration cost of your name to the namespace's designated burn address when you renew it. When a name expires, it enters a \"grace period\". The period is set to 5000 blocks (a month) but can be configured for each namespace. + +It will stop resolving in the grace period, and all of the above operations will cease to be honored by the BNS consensus rules. You may, however, send a NAME_RENEWAL during this grace period to preserve your name. After the grace period, everybody can register that name again. If your name is in a namespace where names do not expire, then you never need to use this transaction. + +### name-revoke + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(name-revoke namespace name)` + +#### Description: + +Makes a name unresolvable. The BNS consensus rules stipulate that once a name is revoked, no one can change its public key hash or its zone file hash. The name's zone file hash is set to null to prevent it from resolving. You should only do this if your private key is compromised, or if you want to render your name unusable for whatever reason. + +### name-transfer + +#### Input: `(buff 20), (buff 48), principal, (optional (buff 20))` + +#### Output: `(response bool int)` + +#### Signature: `(name-transfer namespace name new-owner zonefile-hash)` + +#### Description: + +Changes the name's public key hash. You would send a name transfer transaction if you wanted to: + +- Change your private key +- Send the name to someone else or +- Update your zone file + +When transferring a name, you have the option to also clear the name's zone file hash (i.e. set it to null). This is useful for when you send the name to someone else, so the recipient's name does not resolve to your zone file. + +### name-update + +#### Input: `(buff 20), (buff 48), (buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(name-update namespace name zonefile-hash)` + +#### Description: + +Changes the name's zone file hash. You would send a name update transaction if you wanted to change the name's zone file contents. For example, you would do this if you want to deploy your own Gaia hub and want other people to read from it. + +### namespace-preorder + +#### Input: `(buff 20), uint` + +#### Output: `(response uint int)` + +#### Signature: `(namespace-preorder hashed-salted-namespace stx-to-burn)` + +#### Description: + +Registers the salted hash of the namespace with BNS nodes, and burns the requisite amount of cryptocurrency. Additionally, this step proves to the BNS nodes that user has honored the BNS consensus rules by including a recent consensus hash in the transaction. Returns pre-order's expiration date (in blocks). + +### namespace-ready + +#### Input: `(buff 20)` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-ready namespace)` + +#### Description: + +Launches the namespace and makes it available to the public. Once a namespace is launched, anyone can register a name in it if they pay the appropriate amount of cryptocurrency. + +### namespace-reveal + +#### Input: `(buff 20), (buff 20), uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, uint, principal` + +#### Output: `(response bool int)` + +#### Signature: `(namespace-reveal namespace namespace-salt p-func-base p-func-coeff p-func-b1 p-func-b2 p-func-b3 p-func-b4 p-func-b5 p-func-b6 p-func-b7 p-func-b8 p-func-b9 p-func-b10 p-func-b11 p-func-b12 p-func-b13 p-func-b14 p-func-b15 p-func-b16 p-func-non-alpha-discount p-func-no-vowel-discount lifetime namespace-import)` + +#### Description: + +Reveals the salt and the namespace ID (after a namespace preorder). It reveals how long names last in this namespace before they expire or must be renewed, and it sets a price function for the namespace that determines how cheap or expensive names its will be.All of the parameters prefixed by `p` make up the `price function`. These parameters govern the pricing and lifetime of names in the namespace. + +The rules for a namespace are as follows: + +- a name can fall into one of 16 buckets, measured by length. Bucket 16 incorporates all names at least 16 characters long. + +- the pricing structure applies a multiplicative penalty for having numeric characters, or punctuation characters. + +- the price of a name in a bucket is `((coeff) * (base) ^ (bucket exponent)) / ((numeric discount multiplier) * (punctuation discount multiplier))` + +Example: + +- base = 10 +- coeff = 2 +- nonalpha discount: 10 +- no-vowel discount: 10 +- buckets 1, 2: 9 +- buckets 3, 4, 5, 6: 8 +- buckets 7, 8, 9, 10, 11, 12, 13, 14: 7 +- buckets 15, 16+: + +## Read-only functions + +### can-name-be-registered + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(can-name-be-registered namespace name)` + +#### Description: + +Returns true if the provided name can be registered. + +### can-namespace-be-registered + +#### Input: `(buff 20)` + +#### Output: `(response bool UnknownType)` + +#### Signature: `(can-namespace-be-registered namespace)` + +#### Description: + +Returns true if the provided namespace is available. + +### can-receive-name + +#### Input: `principal` + +#### Output: `(response bool int)` + +#### Signature: `(can-receive-name owner)` + +#### Description: + +Returns true if the provided name can be received. That is, if it is not currently owned, a previous lease is expired, and the name wasn't revoked. + +### get-name-price + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response uint int)` + +#### Signature: `(get-name-price namespace name)` + +#### Description: + +Gets the price for a name. + +### get-namespace-price + +#### Input: `(buff 20)` + +#### Output: `(response uint int)` + +#### Signature: `(get-namespace-price namespace)` + +#### Description: + +Gets the price for a namespace. + +### get-namespace-properties + +#### Input: `(buff 20)` + +#### Output: `(response (tuple (namespace (buff 20)) (properties (tuple (can-update-price-function bool) (launched-at (optional uint)) (lifetime uint) (namespace-import principal) (price-function (tuple (base uint) (buckets (list 16 uint)) (coeff uint) (no-vowel-discount uint) (nonalpha-discount uint))) (revealed-at uint)))) int)` + +#### Signature: `(get-namespace-properties namespace)` + +#### Description: + +Get namespace properties. + +### is-name-lease-expired + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response bool int)` + +#### Signature: `(is-name-lease-expired namespace name)` + +#### Description: + +Return true if the provided name lease is expired. + +### name-resolve + +#### Input: `(buff 20), (buff 48)` + +#### Output: `(response (tuple (lease-ending-at (optional uint)) (lease-started-at uint) (owner principal) (zonefile-hash (buff 20))) int)` + +#### Signature: `(name-resolve namespace name)` + +#### Description: + +Get name registration details. + +### resolve-principal + +#### Input: `principal` + +#### Output: `(response (tuple (name (buff 48)) (namespace (buff 20))) (tuple (code int) (name (optional (tuple (name (buff 48)) (namespace (buff 20)))))))` + +#### Signature: `(resolve-principal owner)` + +#### Description: + +Returns the registered name that a principal owns if there is one. A principal can only own one name at a time. + +## Error codes + +### ERR_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `4001` + +### ERR_NAMESPACE_ALREADY_EXISTS + +#### type: `int` + +#### value: `1006` + +### ERR_NAMESPACE_ALREADY_LAUNCHED + +#### type: `int` + +#### value: `1014` + +### ERR_NAMESPACE_BLANK + +#### type: `int` + +#### value: `1013` + +### ERR_NAMESPACE_CHARSET_INVALID + +#### type: `int` + +#### value: `1016` + +### ERR_NAMESPACE_HASH_MALFORMED + +#### type: `int` + +#### value: `1015` + +### ERR_NAMESPACE_NOT_FOUND + +#### type: `int` + +#### value: `1005` + +### ERR_NAMESPACE_NOT_LAUNCHED + +#### type: `int` + +#### value: `1007` + +### ERR_NAMESPACE_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `1011` + +### ERR_NAMESPACE_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `1003` + +### ERR_NAMESPACE_PREORDER_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `1009` + +### ERR_NAMESPACE_PREORDER_EXPIRED + +#### type: `int` + +#### value: `1002` + +### ERR_NAMESPACE_PREORDER_LAUNCHABILITY_EXPIRED + +#### type: `int` + +#### value: `1010` + +### ERR_NAMESPACE_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `1001` + +### ERR_NAMESPACE_PRICE_FUNCTION_INVALID + +#### type: `int` + +#### value: `1008` + +### ERR_NAMESPACE_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `1012` + +### ERR_NAMESPACE_UNAVAILABLE + +#### type: `int` + +#### value: `1004` + +### ERR_NAME_ALREADY_CLAIMED + +#### type: `int` + +#### value: `2011` + +### ERR_NAME_BLANK + +#### type: `int` + +#### value: `2010` + +### ERR_NAME_CHARSET_INVALID + +#### type: `int` + +#### value: `2022` + +### ERR_NAME_CLAIMABILITY_EXPIRED + +#### type: `int` + +#### value: `2012` + +### ERR_NAME_COULD_NOT_BE_MINTED + +#### type: `int` + +#### value: `2020` + +### ERR_NAME_COULD_NOT_BE_TRANSFERRED + +#### type: `int` + +#### value: `2021` + +### ERR_NAME_EXPIRED + +#### type: `int` + +#### value: `2008` + +### ERR_NAME_GRACE_PERIOD + +#### type: `int` + +#### value: `2009` + +### ERR_NAME_HASH_MALFORMED + +#### type: `int` + +#### value: `2017` + +### ERR_NAME_NOT_FOUND + +#### type: `int` + +#### value: `2013` + +### ERR_NAME_NOT_RESOLVABLE + +#### type: `int` + +#### value: `2019` + +### ERR_NAME_OPERATION_UNAUTHORIZED + +#### type: `int` + +#### value: `2006` + +### ERR_NAME_PREORDERED_BEFORE_NAMESPACE_LAUNCH + +#### type: `int` + +#### value: `2018` + +### ERR_NAME_PREORDER_ALREADY_EXISTS + +#### type: `int` + +#### value: `2016` + +### ERR_NAME_PREORDER_EXPIRED + +#### type: `int` + +#### value: `2002` + +### ERR_NAME_PREORDER_FUNDS_INSUFFICIENT + +#### type: `int` + +#### value: `2003` + +### ERR_NAME_PREORDER_NOT_FOUND + +#### type: `int` + +#### value: `2001` + +### ERR_NAME_REVOKED + +#### type: `int` + +#### value: `2014` + +### ERR_NAME_STX_BURNT_INSUFFICIENT + +#### type: `int` + +#### value: `2007` + +### ERR_NAME_TRANSFER_FAILED + +#### type: `int` + +#### value: `2015` + +### ERR_NAME_UNAVAILABLE + +#### type: `int` + +#### value: `2004` + +### ERR_PANIC + +#### type: `int` + +#### value: `0` + +### ERR_PRINCIPAL_ALREADY_ASSOCIATED + +#### type: `int` + +#### value: `3001` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md new file mode 100644 index 0000000000..6a204159d3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/stacking-contract.md @@ -0,0 +1,352 @@ +--- +title: Stacking Contract +description: See a detailed list of all functions and error codes of the Stacking contract. +sidebar_position: 6 +--- + +## Introduction + +Stacking is implemented as a smart contract using Clarity. You can always find the Stacking contract identifier using the Stacks Blockchain API [`v2/pox` endpoint](https://docs.hiro.so/api#operation/get_pox_info). + +Below is a list of public and read-only functions as well as error codes that can be returned by those methods: + +- [Public functions](#public-functions) +- [Read-only functions](#read-only-functions) +- [Error codes](#error-codes) + +## Public functions + +### allow-contract-caller + +#### input: `principal, (optional uint)` + +#### output: `(response bool int)` + +#### signature: `(allow-contract-caller caller until-burn-ht)` + +#### description: + +Give a contract-caller authorization to call stacking methods. Normally, stacking methods may only be invoked by _direct_ transactions (i.e., the `tx-sender` issues a direct `contract-call` to the stacking methods). + +By issuing an allowance, the tx-sender may call through the allowed contract. + +### delegate-stack-stx + +#### input: `principal, uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(delegate-stack-stx stacker amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +As a delegate, stack the given principal's STX using `partial-stacked-by-cycle`. + +Once the delegate has stacked > minimum, the delegate should call `stack-aggregation-commit`. + +### delegate-stx + +#### input: `uint, principal, (optional uint), (optional (tuple (hashbytes (buff 20)) (version (buff 1))))` + +#### output: `(response bool int)` + +#### signature: `(delegate-stx amount-ustx delegate-to until-burn-ht pox-addr)` + +#### description: + +Delegate to `delegate-to` the ability to stack from a given address. + +This method _does not_ lock the funds, rather, it allows the delegate to issue the stacking lock. + +The caller specifies: + +- amount-ustx: the total amount of ustx the delegate may be allowed to lock +- until-burn-ht: an optional burn height at which this delegation expiration +- pox-addr: an optional p2pkh or p2sh address to which any rewards _must_ be sent + +### disallow-contract-caller + +#### input: `principal` + +#### output: `(response bool int)` + +#### signature: `(disallow-contract-caller caller)` + +#### description: + +Revokes authorization from a contract to invoke stacking methods through contract-calls + +### reject-pox + +#### input: + +#### output: `(response bool int)` + +#### signature: `(reject-pox)` + +#### description: + +Reject Stacking for this reward cycle. + +`tx-sender` votes all its uSTX for rejection. + +Note that unlike Stacking, rejecting PoX does not lock the tx-sender's tokens: PoX rejection acts like a coin vote. + +### revoke-delegate-stx + +#### input: + +#### output: `(response bool int)` + +#### signature: `(revoke-delegate-stx)` + +#### description: + +Revoke a Stacking delegate relationship. A particular Stacker may only have one delegate, so this method does not take any parameters, and just revokes the Stacker's current delegate (if one exists). + +### stack-aggregation-commit + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint` + +#### output: `(response bool int)` + +#### signature: `(stack-aggregation-commit pox-addr reward-cycle)` + +#### description: + +Commit partially stacked STX. + +This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, + +so long as: + +1. The pox-addr is the same. +2. This \"commit\" transaction is called _before_ the PoX anchor block. + +This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, + +but does not require it be all locked up within a single transaction + +### stack-stx + +#### input: `uint, (tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint` + +#### output: `(response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) int)` + +#### signature: `(stack-stx amount-ustx pox-addr start-burn-ht lock-period)` + +#### description: + +Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). + +The STX will be locked for the given number of reward cycles (lock-period). + +This is the self-service interface. tx-sender will be the Stacker. + +- The given stacker cannot currently be stacking. +- You will need the minimum uSTX threshold. This isn't determined until the reward cycle begins, but this method still requires stacking over the _absolute minimum_ amount, which can be obtained by calling `get-stacking-minimum`. +- The pox-addr argument must represent a valid reward address (p2pkh, p2sh, SegWit, or Taproot). + +The tokens will unlock and be returned to the Stacker (tx-sender) automatically. + +## Read-only functions + +### can-stack-stx + +#### input: `(tuple (hashbytes (buff 20)) (version (buff 1))), uint, uint, uint` + +#### output: `(response bool int)` + +#### signature: `(can-stack-stx pox-addr amount-ustx first-reward-cycle num-cycles)` + +#### description: + +Evaluate if a participant can stack an amount of STX for a given period. + +### get-pox-info + +#### input: + +#### output: `(response (tuple (current-rejection-votes uint) (first-burnchain-block-height uint) (min-amount-ustx uint) (prepare-cycle-length uint) (rejection-fraction uint) (reward-cycle-id uint) (reward-cycle-length uint) (total-liquid-supply-ustx uint)) UnknownType)` + +#### signature: `(get-pox-info)` + +#### description: + +Returns information about PoX status. + +### get-pox-rejection + +#### input: `principal, uint` + +#### output: `(optional (tuple (amount uint)))` + +#### signature: `(get-pox-rejection stacker reward-cycle)` + +#### description: + +Returns the amount of uSTX that a given principal used to reject a PoX cycle. + +### get-stacker-info + +#### input: `principal` + +#### output: `(optional (tuple (amount-ustx uint) (first-reward-cycle uint) (lock-period uint) (pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))))` + +#### signature: `(get-stacker-info stacker)` + +#### description: + +Returns the _current_ stacking information for `stacker. If the information is expired, or if there's never been such a stacker, then returns none. + +### get-stacking-minimum + +#### input: + +#### output: `uint` + +#### signature: `(get-stacking-minimum)` + +#### description: + +Returns the absolute minimum amount that could be validly Stacked (the threshold to Stack in a given reward cycle may be higher than this + +### get-total-ustx-stacked + +#### input: `uint` + +#### output: `uint` + +#### signature: `(get-total-ustx-stacked reward-cycle)` + +#### description: + +Returns the amount of currently participating uSTX in the given cycle. + +### is-pox-active + +#### input: `uint` + +#### output: `bool` + +#### signature: `(is-pox-active reward-cycle)` + +#### description: + +Returns whether or not PoX has been rejected at a given PoX cycle. + +## Error codes + +### ERR_DELEGATION_EXPIRES_DURING_LOCK + +#### type: `int` + +#### value: `21` + +### ERR_DELEGATION_POX_ADDR_REQUIRED + +#### type: `int` + +#### value: `23` + +### ERR_DELEGATION_TOO_MUCH_LOCKED + +#### type: `int` + +#### value: `22` + +### ERR_INVALID_START_BURN_HEIGHT + +#### type: `int` + +#### value: `24` + +### ERR_NOT_ALLOWED + +#### type: `int` + +#### value: `19` + +### ERR_STACKING_ALREADY_DELEGATED + +#### type: `int` + +#### value: `20` + +### ERR_STACKING_ALREADY_REJECTED + +#### type: `int` + +#### value: `17` + +### ERR_STACKING_ALREADY_STACKED + +#### type: `int` + +#### value: `3` + +### ERR_STACKING_EXPIRED + +#### type: `int` + +#### value: `5` + +### ERR_STACKING_INSUFFICIENT_FUNDS + +#### type: `int` + +#### value: `1` + +### ERR_STACKING_INVALID_AMOUNT + +#### type: `int` + +#### value: `18` + +### ERR_STACKING_INVALID_LOCK_PERIOD + +#### type: `int` + +#### value: `2` + +### ERR_STACKING_INVALID_POX_ADDRESS + +#### type: `int` + +#### value: `13` + +### ERR_STACKING_NO_SUCH_PRINCIPAL + +#### type: `int` + +#### value: `4` + +### ERR_STACKING_PERMISSION_DENIED + +#### type: `int` + +#### value: `9` + +### ERR_STACKING_POX_ADDRESS_IN_USE + +#### type: `int` + +#### value: `12` + +### ERR_STACKING_STX_LOCKED + +#### type: `int` + +#### value: `6` + +### ERR_STACKING_THRESHOLD_NOT_MET + +#### type: `int` + +#### value: `11` + +### ERR_STACKING_UNREACHABLE + +#### type: `int` + +#### value: `255` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md new file mode 100644 index 0000000000..e535dcf260 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/noteworthy-contracts/xbtc.md @@ -0,0 +1,28 @@ +--- +title: xBTC +description: Wrapped BTC on Stacks +--- + +![](/img/xbtc-icon.webp) + +## Introduction + +[Wrapped.com](https://www.wrapped.com) has brought Bitcoin (xBTC) to the Stacks ecosystem. + +xBTC is backed 1:1 by Bitcoin and empowers developers to expand the Bitcoin DeFi ecosystem. + +The reserves are publicly visible [here](https://open.wrapped.com/reserves/). + +## Contract + +[SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin](https://explorer.stacks.co/txid/SP3DX3H4FEYZJZ586MFBS25ZW3HZDMEW92260R2PR.Wrapped-Bitcoin?chain=mainnet) + +## Examples of uses + +[Friedger Mining Pool](https://pool.friedger.de/) currently supports Stacking rewards payments in xBTC (optional). + +## More information + +- [Blog post announcement](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc) by Muneeb Ali + +- Video: [Why xBTC is Important For Bitcoin to Grow](https://www.youtube.com/watch?v=xIoadrfSdi4) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md new file mode 100644 index 0000000000..adb12a58fd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/sample-contracts.md @@ -0,0 +1,14 @@ +--- +title: Sample Contracts +description: Example contracts for learning and building Clarity smart contracts. +sidebar_position: 5 +--- + +Here's a list of sample contracts to learn Clarity or to serve as a starting point for your next project. All contracts come from the [Clarity book](https://book.clarity-lang.org/) and have been audited by [Coinfabrik](https://www.coinfabrik.com/). + +- [Counter](https://github.com/clarity-lang/book/tree/main/projects/counter) +- [Multisig Vault](https://github.com/clarity-lang/book/tree/main/projects/multisig-vault) +- [Sip-009 NFT](https://github.com/clarity-lang/book/tree/main/projects/sip009-nft) +- [SIP-010 FT](https://github.com/clarity-lang/book/tree/main/projects/sip010-ft) +- [Timelocked Wallet](https://github.com/clarity-lang/book/tree/main/projects/timelocked-wallet) +- [Tiny Market (NFT marketplace)](https://github.com/clarity-lang/book/tree/main/projects/tiny-market) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/security/decidable.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/security/decidable.md new file mode 100644 index 0000000000..2920f647a7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/security/decidable.md @@ -0,0 +1,174 @@ +--- +title: Decidability +description: An exploration of the security advantages that come with a non-Turing complete, decidable language +sidebar_label: Decidability +sidebar_position: 1 +--- + +## What does it mean for a language to be Non-Turing Complete or Decidable? + +Non-Turing complete and decidable are two terms you will often hear about the security advantages of Clarity, but what do they mean? + +While related, they are not quite interchangeable, since there are a few differences. + +### Non-Turing Complete + +A system or language is non-Turing complete if it cannot simulate a Turing machine, which is an abstract model of computation. Non-Turing complete systems have limited computational power compared to Turing complete systems. A Turing-complete system or language can simulate any Turing machine. Examples of non-Turing complete systems include finite state machines and some domain-specific languages (like Clarity). + +Non-Turing complete languages typically cannot express all possible algorithms. Specifically, some problems whose solutions require unbounded loops or recursion cannot be expressed using non-Turing complete languages. This last property is especially important in the context of Clarity, as it makes it so that features like unbounded loops and reentrancy are disallowed at a language level. + +### Decidable + +A problem is decidable if there exists an algorithm that can always determine whether a given input has a particular property or not in a finite amount of time. In other words, a decidable problem can be solved by a Turing machine that is guaranteed to halt for all input instances. Decidability is a property of problems, whereas Turing completeness is a property of languages or computational systems. + +The fact that Clarity is decidable means that developers (and tooling) can more easily reason about and predict with certainty the behavior of Clarity contracts, regardless of the input. + +## Mindset of a Smart Contract Developer + +Before we dive into specifics, let's first set the context and viewpoint we should hold as smart contract developers who want to write secure code. + +As you explore further into the security properties of Solidity and Clarity, you'll see that there are always mitigation steps that _can_ be taken by developers to help address some of these security issues. + +The main issue, with this line of thinking, is it increases the odds of human error in smart contract security. If we can preserve functionality while mitigating the chance of human error as much as possible, we should do so. + +## Should smart contracts be Turing complete? + +We will discover new applications for smart contracts. These applications will go beyond current smart contracts, traditional contracts, and may even open new economic opportunities. Given these possibilities, how should we build our smart contracts? What characteristics should our smart contract languages have? + +It is good practice to separate data from programs. Should smart contracts be data, or programs, or something in between? If smart contracts are data, then should the programs that execute-them be Turing complete or perhaps less powerful? If smart contracts are programs, then what language should smart contracts be written in? What characteristics should this programming language have? + +The Church-Turing thesis is the hypothesis that all formal notions of computation are captured by Turing machines or modern computers. A programming language is Turing complete if it captures all formal notions of computation. Many programming languages are Turing complete. For example, Python, C++, Rust, Java, Lisp, and Solidity are all Turing complete. + +Consider a program and its input. In the worst case, determining this program’s output is impossible. Validating a program, on a particular input, is done by generating a proof-of-correctness. + +Proofs-of-correctness are logical proofs that can be mechanically validated. Finding proofs-of-correctness for programs and their input is undecidable. Kurt G\”odel showed there are undecidability logical statements. + +This indicates all programs in Turing complete languages cannot be validated in the worst case. Thus, Turing complete smart contract languages must allow contracts that cannot be validated. + +Alonzo Church and Alan Turing showed there are problems that are uncomputable. Uncomputable problems cannot be solved by any Turing machine. Hence, assuming the Church-Turing thesis, these uncomputable problems cannot be solved by any computer. + +We'll explore this idea further later in this section. + +Turing complete languages are very expressive. In fact, assuming the Church-Turing thesis, Turing complete languages are as expressive as possible in some sense. + +Is there a trade-off? What types of problems can occur with uncomputable problems and programs whose validity may be undecidable? + +As smart contracts subsume parts of contract law, consider the large body of laws and regulations for tax law. + +For instance, US tax law and regulations take up several million words. International tax law and regulations pushes these numbers much higher. + +Are these laws and regulations programs or are they data? If tax law were to be written in a Turing complete language, then the law may codify uncomputable problems. It is an accountant’s nightmare for their advice to be undecidable. + +Clarity is non-Turing complete, yet very expressive. This makes it so that Clarity is decidable and cannot encode uncomputable problems. There are discussions and papers on smart contract languages such as Solidity that propose subsets of Solidity that are non-Turing complete. These subsets are decidable and cannot encode uncomputable problems. However, there is no consensus on which subsets to work with and they are not widely used. + +## Advantages of Decidability in Smart Contracts + +Why is decidability important in the context of smart contracts? + +First, it is not possible for a Clarity call to run out of gas in the middle of a call. Because of its decidability, it is possible to get a complete static analysis of the call graph to get an accurate picture of the cost before execution. + +Solidity allows for unbounded loops, recursion, and dynamic function calls, which makes it difficult to accurately predict the execution cost or gas usage beforehand. As a result, Solidity contracts may run out of gas during execution if the gas limit is not set appropriately or if the contract encounters a scenario with unexpectedly high computational requirements. + +One practical example is the issue of a specific kind of DoS attack in Solidity, where the contract is rendered inoperable because of unbounded execution constraints. An example of this is the GovernMental attack, where a mapping that needed to be deleted for a payout became so large that working with it exceeded the block gas limit. + +There are a few different properties of Clarity's language design that prevents such DoS attacks. + +The reason that the analysis system can accurately estimate the execution cost is because certain functionality is intentionally limited in Clarity. + +For example, there is no recursion in Clarity, so we can't infinitely call into a function over and over. + +Data types in Clarity are also restricted. Any data types that don't require a hard length limit are not iterable. + +Maps and tuples, for example, do not require you to enter a maximum length when defining them, but you also can't iterate over them. + +Lists, on the other hand, which are iterable, do require the developer to define an upper limit when defining them. This is a large part of what allows an accurate static analysis of Clarity contracts. + +So how would we implement a mapping of an undefined size in Clarity? We wouldn't, because it's an anti-pattern in smart contract design. + +Instead, Clarity forces us to think of a better solution to our problem. For example, implementing a way for users to handle mapping/list element operations themselves, instead of mass operations handled at the contract level. + +If you [analyze the GovernMental attack](https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8#h-attack-2-call-stack-attack), you'll see that it took advantage of multiple security issues, all of which are mitigated in Clarity. You'll also see that a fix was added to make it economically infeasible to carry out this type of attack again. + +This brings up another crucial point when setting appropriate mental models for smart contracts and blockchain systems: complexity means more potential bugs, which means adding more complexity to address those bugs. + +When this happens over and over again, we are trapping ourselves into creating an evermore complex system. Addressing these issues at the language level prevents this ever-growing complexity. + +For a deep dive into how Clarity was designed, check out [SIP-002](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md). + +:::note +You can view some more common smart contract vulnerabilities and how they are mitigated in [this article](https://stacks.org/bringing-clarity-to-8-dangerous-smart-contract-vulnerabilities/). +::: + +This has second-order effects as well when we look at security testing and auditing. One of the common tools for testing smart contracts is formal verification, where we mathematically prove that certain properties of smart contracts will or will not remain true in all cases. + +This can lead to the path explosion problem, where there are so many paths available that formal verification becomes incredibly difficult. This problem is mitigated in Clarity, since there is not chance of a program encountering an unbounded loop. + +This leads us to a more general mental model for thinking about decidability as smart contracts continue to become a larger part of our economy. Remember that the goal with blockchain systems is to create an open, transparent, fair financial system. + +This means that smart contracts will be responsible for managing large amounts of wealth for ever-growing amounts of people. As smart contracts encompass more financial structures, their complexity and usage will grow. + +Complexity is the enemy of security. The more complex a system is, the more danger there is in creating uncomputable problems when there are no hard restrictions on the execution steps that can be taken. + +This is deadly in financial infrastructure that is not only open and transparent, but immutable. Let's explore this idea of uncomputability a bit more. + +## Intuition on Uncomputability + +Intuitively, uncomputability is an algorithmic view of undecidability. Uncomputability has the same foundations as undecidability. Undecidable questions are framed as logic statements or statements about integers. Of course, programs are logic statements and may even be viewed as integers, though we view programs differently. We often view programs with additional details of memory models, implementation details, and execution semantics. + +The [Halting problem](https://en.wikipedia.org/wiki/Halting_problem#:~:text=In%20computability%20theory%2C%20the%20halting,or%20continue%20to%20run%20forever.): As an example, given any program `P` and any finite input `I` for `P`, then the Halting Problem is the challenge of determining if `P` halts on input `I`. + +Alonzo Church and Alan Turing showed the Halting Problem is unsolvable. + +Christopher Strachey gave an intuitive proof-by-contradiction showing the Halting problem is uncomputable. This is set up by supposing there is a program `H` that can solve the Halting problem for any program `P`. `H(P)` returns true if `P` halts and false otherwise. Then build a program `P` that does not halt when `H(P)` is true, giving a contradiction. Similarly, this program `P` halts when `H(P)` is false, also a contradiction. + +Uncomputable problems are problems that cannot be solved by an algorithm or a computer, no matter how much time or resources are provided. These problems exist in various forms, and one such example is the Post correspondence problem, which was proposed by Emil Post. + +The Post correspondence problem can be described using pairs of strings and an integer. Imagine you have n pairs of strings, called P. These strings are made up of characters from a character set, such as UTF-8 or any other alphabet with at least two symbols. The pairs of strings look like this: + +`P = { (x1, y1), (x2, y2), … , (xn, yn) }` + +Now, you also have an integer `m` that is greater than 0. The Post correspondence problem asks whether there is a way to create a list of indices `(i1, i2, …, im)` using the given pairs of strings. You can repeat these indices if needed, with one condition: when you combine the `x` strings from the pairs using the indices, the resulting string must be equal to the combined `y` strings from the same pairs using the same indices. In other words: + +`x(i1) x(i2) … x(im) = y(i1) y(i2) … y(im)` + +When developers try to solve the Post correspondence problem, they often attempt to use indeterminate loops (loops without a fixed number of iterations) rather than recursion. This is because the problem seems to require searching through different combinations of indices until a solution is found or it's proven that no solution exists. + +In simple terms, the Post correspondence problem involves trying to find a sequence of indices that, when applied to the given pairs of strings, produces equal concatenated strings from both the `x` and `y` components. This problem is considered uncomputable because there is no general algorithm that can solve it for all possible input pairs of strings and integers. + +It turns out, many questions about how programs behave are uncomputable. This has a number of consequences for smart contracts that are built in Turing complete languages, many of which we are not aware of yet but will surely become aware of as we encounter them in the future. + +## Raymond Smullyan’s Intuition on Undecidability + +This is a part of Raymond Smullyan’s approach to understanding undecidability in propositional logic. It uses meta-information to show something must be true, though it cannot be proved in propositional logic. This is based on a paradox. + +In propositional logic, a logical statement is undecidable if we cannot prove it true or false. Given a propositional logic statement S, a proof is a sequence of formal logical deductions, starting from basic facts and ending by indicating if S is true or false. + +Smullyan’s starts with an island of Knights and Knaves. Knights always tell the truth. Knaves always lie. We cannot distinguish islanders otherwise. + +There is a great logician named Ray. Whatever Ray proves is true. This is just like a good theorem prover. + +An islander Jack proclaims: “You cannot prove I am a Knight” to the logician Ray. + +The next reasoning is based on meta-knowledge of this situation. This meta-knowledge shows that some problems are undecidable in propositional logic. + +If Ray can prove Jack is a Knight, then Jack must be a Knave, since Jack must have lied. That is because Ray proved Jack is a Knight. Since Jack is a Knave, Ray’s proof contradicts the assumption that Ray only proves true things. So, this case cannot hold. + +If Ray cannot prove Jack is a Knight, then Jack must be a Knight, since Jack stated the truth. But Ray cannot prove the fact that Jack is a Knight. + +In the context of smart contracts and programming languages, Turing complete languages like Solidity come with the possibility of undecidable problems. + +These undecidable problems are similar to the paradox presented in the Knights and Knaves story, where it's impossible to determine whether Jack is a Knight or a Knave based on the given information. + +In the Knights and Knaves story, Ray is analogous to a theorem prover or a smart contract in a Turing complete language. Ray is faced with a statement that is undecidable within the constraints of the system (Knights and Knaves), which leads to a paradox. + +Similarly, a Turing complete smart contract language might face undecidable problems that can't be resolved, leading to unexpected behavior, vulnerabilities, or resource consumption issues (like running out of gas in Ethereum). + +On the other hand, non-Turing complete languages like Clarity are designed to avoid undecidable problems by limiting their expressiveness. + +In the context of the Knights and Knaves story, a non-Turing complete language would simply not allow Jack to make a statement that could lead to a paradox. By disallowing certain features like unbounded loops and recursion, non-Turing complete languages can provide stronger guarantees about the behavior and resource usage of smart contracts. + +This predictability is desirable in many cases, especially when dealing with high-value transactions or critical systems. + +## Reference + +The Mathematics of Various Entertaining Subjects: Research in Recreational Math Illustrated Edition, Jennifer Beineke (Editor), Jason Rosenhouse (Editor), Raymond M. Smullyan (Foreword), Princeton University Press, 2016. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/clarity/security/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/security/index.md new file mode 100644 index 0000000000..90aa31abb4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/clarity/security/index.md @@ -0,0 +1,22 @@ +--- +title: Clarity Security +description: Deep dives into the different security properties of Clarity +sidebar_label: Security +sidebar_position: 4 +--- + +Clarity has been purpose-built from the ground up to write safe, secure smart contracts. This gives a number of unique properties not seen in other smart contract languages like Solidity. + +If you are coming from a Solidity background, or wondering why you should bother learning a new language like Clarity, security is one of the top reasons. Every design decision for Clarity has been made with this in mind. + +This section will dive deeper into some of these concepts and properties to dig into the security advantages of using Clarity. + +We'll cover conceptual and practical examples, often comparing Clarity to similar functionality in Solidity to demonstrate the unique security advantages of Clarity. + +This section is a work in progress and [contributions are always welcome](../../contribute/). + +## Non-Turing Complete + +This is an often-discussed property of Clarity, and is in contrast to Solidity and most other languages, which are Turing-complete. Turing-completeness is often seen as an advantage and a necessity in fully-expressive languages, but it comes with some dangers and disadvantages that we'll explore in this section. + +[Read More](./decidable.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/contribute/docs.md b/i18n/zh/docusaurus-plugin-content-docs/current/contribute/docs.md index 38c3e19d43..4732eb19e9 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/contribute/docs.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/contribute/docs.md @@ -7,7 +7,7 @@ description: Learn how this site is built, and how you can contribute to it. Welcome. Thank you for your interest in contributing and helping make these docs as good as they can be. -This docs site is built on the open source platform [Discosaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). +This docs site is built on the open source platform [Docusaurus 2](https://docusaurus.io/) and most of its content is written in Markdown files. All of the code for this site is free and open source, located at the [GitHub repository here](https://github.com/stacks-network/docs). :::tip Don't know what Markdown is? Want to learn? :::tip Don't know what Markdown is? Want to learn? Here is a [helpful guide](https://guides.github.com/features/mastering-markdown/). @@ -15,7 +15,7 @@ Don't want to learn it? No need to. Don't want to learn it? No need to. Write [i :::info You need a free [Github](https://www.github.com) account to add or edit any content. ::: ::: -To edit any page, just click on the *Edit this page* button at the bottom of each page and submit your changes online. +To edit any page, just click on the _Edit this page_ button at the bottom of each page and submit your changes online. To add new content, they are two different ways to do it, the [easy way](#easy-way) and the [advanced way](#advanced-way). @@ -24,28 +24,32 @@ To add new content, they are two different ways to do it, the [easy way](#easy-w [**Simply click here and enter the text of the article you wish to add.**](https://github.com/stacks-network/docs/issues/new?assignees=&labels=documentation&template=add-documentation.md&title=%5BAdd+docs%5D) This will open up an issue on github using our template. + ## Advanced way For more advanced changes you can follow the next steps. You can also test the site locally using this method. + ### Steps -1. Fork the [docs reposiroty](https://github.com/stacks-network/docs) by clicking on the *Fork* button in the upper right of the screen. +1. Fork the [docs repository](https://github.com/stacks-network/docs) by clicking on the _Fork_ button in the upper right of the screen. 2. Clone your fork to your local machine with this command `git clone git@github.com:/docs.git stacks_docs` 3. Enter your project folder `cd stacks_docs` 4. Create a branch `git checkout -b feat/my-feature-branch`. 5. You can optionally preview your changes in real time with: - - `npm install` (to install dependencies). - - `npx docusaurus start` to start a local copy of the site. `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of yourhanges in real time. + - `npm install` (to install dependencies). + - `npx docusaurus start` to start a local copy of the site. A web browser will open at http://localhost:3000, so you can see a preview of your changes in real time. 6. Make the changes you wish and then commit them with this kind of message: `git commit -am "feat: some new feature or content"`. 7. Push to to GitHub with `git push --set-upstream origin feature/my-feature-branch`. 8. Visit GitHub and make your pull request. -## Aditional information +## Additional information + ### Running and building the site locally (optional) You can start the page locally with the following command. This is enough to preview your changes. This is enough to preview your changes. + ```bash npx docusaurus start ``` @@ -54,8 +58,8 @@ Before running this command for the first time you will need to run `npm install The docs site will be accessible at this url: [`http://localhost:3000`](http://localhost:3000). - After you finished your changes, you can also build the entire site with the following command (not usually needed): + ```bash npm run build ``` @@ -91,7 +95,7 @@ All the docs in English are stored in the folder `/docs/`. To add new English content simply add a markdown file (.md) into any subfolder in docs, and it will be automatically displayed in the category of that folder. -All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. +All the docs in other languages are stored under the folder `i18n`, but these files should never be edited using GitHub as they are overwritten by Crowdin every time new translations are added. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. **To make changes in other languages**, you must do so using Crowdin. Please refer to [translations](translations) instead. ### Frontmatter @@ -124,6 +128,7 @@ And execute prettier with the following command: npx prettier --write mynewfiletocheck.md ``` --> + ### Use Conventional Commits We use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as and commits naming convention. Use it while contributing, please. Use it while contributing, please. Use it while contributing, please. @@ -138,6 +143,7 @@ To write a code block, you need to wrap your code in ` ```language `, and end yo (define-public (get-counter) (ok (var-get counter))) ``` + ### Admonitions You can use the following admonitions to highlight content. @@ -234,4 +240,4 @@ Some **content** with _markdown_ `syntax`. Check [this `api`](#). Some **content** with _markdown_ `syntax`. Check [this `api`](#). -::: \ No newline at end of file +::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/contribute/translations.md b/i18n/zh/docusaurus-plugin-content-docs/current/contribute/translations.md index fa419be8be..37b1fb40c9 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/contribute/translations.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/contribute/translations.md @@ -1,12 +1,11 @@ --- title: Contribute with translations -description: Want to help tranlating these docs to your local language? +description: Want to help translating these docs to your local language? --- ## Help with translations -Translations are managed with Crowdin. -Anybody can colaborate and no technichal skills are required, as it's all done on the browser. +Translations are managed with Crowdin. Anybody can collaborate and no technical skills are required, as it's all done on the browser. To help with translation please go to [this page](https://crowdin.com/project/docsstacksco), click any language and start translating. @@ -14,13 +13,13 @@ All help is appreciated. :::caution Please don't add any translations to the Github repository, as the translated pages get rewritten from Crowdin. Translations need to be added on Crodin intead. -::: Translations need to be added on Crodin intead. +::: Translations need to be added on Crowdin instead. ::: ### Common issues on translations When translating in Crowdin, please only translate the texts and not the html code. -If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. These errors will prevent your translation getting published until the tags are left as they were in the original text. +If you accidentally modify the html tags you will get errors like shown below (`Seems like some formatting tags are missing` or `Translation contains tag that source text doesn't have`). If you acccidently modify the html tags you will get errors like shown below (`Seems like some formating tags are missing` or `Translation contains tag that source text doesn't have`). These errors will prevent your translation getting published until the tags are left as they were in the original text. These errors will prevent your translation getting published until the tags are left as they were in the original text. ![](/img/crowdin-qa-issue-formatting_tags_missing.png) ![](/img/crowdin-qa-issue-tag_source.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md new file mode 100644 index 0000000000..4e3bad99d2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/creating-an-ft.md @@ -0,0 +1,99 @@ +--- +title: Creating a Fungible Token +description: Clarity and Stacks.js code required to make a FT +--- + +Much the same as creating an NFT, Clarity also makes creating a fungible token (FT) trivial as well. + +The process and code are much the same. + +## Trait + +Just like with the NFT, it's a good idea to create a trait when you create a fungible token so that different tools and protocols and be confident in building interfaces for those tokens. + +Since FTs may be divisible, the [FT official mainnet deployment trait address](https://explorer.stacks.co/txid/0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387?chain=mainnet) has additional functions. + +```clarity +(define-trait sip-010-trait + ( + ;; Transfer from the caller to a new principal + (transfer (uint principal principal (optional (buff 34))) (response bool uint)) + + ;; the human readable name of the token + (get-name () (response (string-ascii 32) uint)) + + ;; the ticker symbol, or empty if none + (get-symbol () (response (string-ascii 32) uint)) + + ;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token + (get-decimals () (response uint uint)) + + ;; the balance of the passed principal + (get-balance (principal) (response uint uint)) + + ;; the current total supply (which does not need to be a constant) + (get-total-supply () (response uint uint)) + + ;; an optional URI that represents metadata of this token + (get-token-uri () (response (optional (string-utf8 256)) uint)) + ) +) +``` + +Now let's see how we might implement this in Clarity, just like we would an NFT. + +## Clarity Code + +```clarity +(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) + + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +;; No maximum supply! +(define-fungible-token clarity-coin) + +(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34)))) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (try! (ft-transfer? clarity-coin amount sender recipient)) + (match memo to-print (print to-print) 0x) + (ok true) + ) +) + +(define-read-only (get-name) + (ok "Clarity Coin") +) + +(define-read-only (get-symbol) + (ok "CC") +) + +(define-read-only (get-decimals) + (ok u6) +) + +(define-read-only (get-balance (who principal)) + (ok (ft-get-balance clarity-coin who)) +) + +(define-read-only (get-total-supply) + (ok (ft-get-supply clarity-coin)) +) + + +(define-read-only (get-token-uri) + (ok none) +) + + +(define-public (mint (amount uint) (recipient principal)) + (begin + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (ft-mint? clarity-coin amount recipient) + ) +) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md new file mode 100644 index 0000000000..851189579e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/creating-an-nft.md @@ -0,0 +1,87 @@ +--- +title: Creating an NFT +description: Clarity and Stacks.js code required to make an NFT +--- + +Clarity makes creating NFTs incredibly easy. With built-in functions for creating and working with the token, you can have an NFT created in less than 10 minutes of work. + +Let's see how. + +:::tip +For a more in-depth discussion of NFTs in Clarity and how to create them, check out the [NFTs chapter in the Clarity book](https://book.clarity-lang.org/ch10-01-sip009-nft-standard.html). +::: + +## Trait + +The first thing we need when we create an NFT is a trait. A trait is an interface that allows us to create an NFT with a defined set of functions. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. + +By implementing a trait that the community agrees on, all protocols and products know how they can interact with an NFT. + +The official mainnet trait can be [found on the Stacks Explorer](https://explorer.stacks.co/txid/0x80eb693e5e2a9928094792080b7f6d69d66ea9cc881bc465e8d9c5c621bd4d07?chain=mainnet) and looks like this: + +```clarity +(define-trait nft-trait + ( + ;; Last token ID, limited to uint range + (get-last-token-id () (response uint uint)) + + ;; URI for metadata associated with the token + (get-token-uri (uint) (response (optional (string-ascii 256)) uint)) + + ;; Owner of a given token identifier + (get-owner (uint) (response (optional principal) uint)) + + ;; Transfer from the sender to a new principal + (transfer (uint principal principal) (response bool uint)) + ) +) +``` + +All we are doing here is defining the function signatures for functions we'll need to implement in out Clarity contract, which we can see a simple version of below. + +## Clarity Code + +This is the Clarity code we need in order to create an NFT, with one additional function, `mint` that allows us to actually create a new NFT. This `mint` function is not needed to adhere to the trait. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) + +(define-non-fungible-token amazing-aardvarks uint) + +(define-data-var last-token-id uint u0) + +(define-constant contract-owner tx-sender) +(define-constant err-owner-only (err u100)) +(define-constant err-not-token-owner (err u101)) + +(define-read-only (get-last-token-id) + (ok (var-get last-token-id)) +) + +(define-read-only (get-token-uri (token-id uint)) + (ok none) +) + +(define-read-only (get-owner (token-id uint)) + (ok (nft-get-owner? amazing-aardvarks token-id)) +) + +(define-public (transfer (token-id uint) (sender principal) (recipient principal)) + (begin + (asserts! (is-eq tx-sender sender) err-not-token-owner) + (nft-transfer? amazing-aardvarks token-id sender recipient) + ) +) + +(define-public (mint (recipient principal)) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (try! (nft-mint? amazing-aardvarks token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md new file mode 100644 index 0000000000..d6ef942f94 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/get-sats-per-stx.md @@ -0,0 +1,27 @@ +--- +title: Get Sats per STX Price +description: Use built-in Clarity functions to retrieve the on-chain exchange rate between BTC and STX +--- + +Utilizing the built-in Clarity function `get-block-info?` we can create what is essentially an on-chain Bitcoin price oracle. We can do this by taking the amount of Bitcoin spent by miners and the block reward earned by those miners to get the sats per stx ratio. + +Let's see how to do this. + +```clarity +(define-read-only (get-sats-per-stx (block uint)) + (let + ( + (miner-spend (unwrap! (get-block-info? miner-spend-winner block) (err "no miner spend"))) + (block-reward (unwrap! (get-block-info? block-reward block) (err "no block reward"))) + (sats-per-stx (/ miner-spend block-reward)) + ) + (ok sats-per-stx) + ) +) +``` + +Here we are defining a read-only function. + +If we deploy this function up to testnet, we can run it in the sandbox. + +I actually have deployed this and you can check it out on the explorer and pass in whatever block you want to get the sats/stx ratio. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/index.md new file mode 100644 index 0000000000..9a40e62b46 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/index.md @@ -0,0 +1,64 @@ +--- +title: Cookbook +description: Code snippets and examples for building Stacks apps +sidebar_label: Cookbook +sidebar_position: 7 +--- + +The Stacks Cookbook is a collection of sample apps and smart contracts to serve as starting points and references for building your own Stacks apps. It is currently a work in progress. Here is some of the content we have planned and we welcome [contributions](../contribute/). + +Many of these cookbook recipes have been pulled from other tutorials and linked here for easy access. Links to full tutorials and sample code have been included for reference and further exploration. + +Got an idea you think would make a good addition? We're always [accepting contributions](../contribute/). + +## Bitcoin Integration + +[Sending Bitcoin with Hiro wallet](./sending-bitcoin-with-hiro-wallet.md) + +Getting a Stacks address from a public key + +[Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) + +Get Sats per STX price + +[Parsing a Bitcoin transaction](./parse-a-btc-tx.md) + +## DAOs + +Creating a simple DAO with ExecutorDAO + +Creating a BTC-backed DAO treasury + +## Tokens + +[Creating an NFT](./creating-an-nft) + +[Creating a Fungible Token](./creating-an-ft.md) + +Minting an NFT with Bitcoin + +## Stacking and Mining + +Simple stacking pool + +Continuous stacking + +Simple mining pool + +Proof of PoX payout + +## Frontend + +[Post conditions with Stacks.js](./post-conditions) + +[Authentication with Stacks.js](./stacks-js-auth) + +[Sending transactions with Stacks.js](./stacks-js-sending-transactions) + +Authenticating with Sign in with Stacks + +## Complete Apps + +[Sup](https://github.com/kenrogers/sup) + +[Hello Stacks](https://github.com/kenrogers/hello-stacks) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md new file mode 100644 index 0000000000..f42dcee690 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/parse-a-btc-tx.md @@ -0,0 +1,53 @@ +--- +title: Parse the Data from a Bitcoin Transaction +description: Use the Clarity-Bitcoin library to parse a Bitcoin transaction +--- + +While we can verify that a transaction was mined using a library and Clarity's built-in functions, as outlined in the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) docs, we can parse a Bitcoin transaction using Clarity as well. + +This doesn't actually require having access to the chain, all we need is the raw transaction hex. + +If you aren't familiar with how Bitcoin transactions are encoded in raw form, take a quick look at that. + +The short version is that all of the data from a Bitcoin transaction is encoded in hex form in a string of numbers, we can slice out pieces of that hex value to pull out all of our transaction data. + +The process to do this is relatively complex, but the Clarity-Bitcoin library comes with a function called `parse-tx` that makes this simple. + +All we need to do is pass it a raw transaction hex and we can get back the data of the transaction, including inputs and outputs. + +:::caution +Note that currently the library only supports legacy transactions, although work to support segwit and taproot transactions is currently underway. +::: + +You can view a [deployed version of the library](https://explorer.hiro.so/txid/0xd493b9ada8899be8773d3f55b21d300ef83ac5c0dd38c8a4dd52a295bd71d539?chain=mainnet) on the explorer and the [GitHub repo here](https://github.com/friedger/clarity-bitcoin). + +The `parse-tx` function looks like this. + +```clarity +(define-read-only (parse-tx (tx (buff 1024))) + (let ((ctx { txbuff: tx, index: u0}) + (parsed-version (try! (read-uint32 ctx))) + (parsed-txins (try! (read-txins (get ctx parsed-version)))) + (parsed-txouts (try! (read-txouts (get ctx parsed-txins)))) + (parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))) + (ok {version: (get uint32 parsed-version), + ins: (get txins parsed-txins), + outs: (get txouts parsed-txouts), + locktime: (get uint32 parsed-locktime)}))) +``` + +We can get the raw transaction hex from a Bitcoin block explorer API like mempool, and it will be returned back to use looking something like this: + +`0200000000010196277c04c986c1ad78c909287fd12dba2924324699a0232e0533f46a6a3916bb0100000000ffffffff026400000000000000160014274ae586ad2035efb4c25049c155f98310d7e106ca16440000000000160014599bcef6387256c6b019030c421b4a4d382fe2600247304402204d94a1e4047ca38a450177ccb6f88585ca147f1939df343d8ac5d962c5f35bb302206f7fa42c21c47ebccdc460393d35c5dfd3b6f0a26cf10fac23d3e6fab71835c20121020cb972a66e3fb1cdcc9efcad060b4457ebec534942700d4af1c0d82a33aa13f100000000`. + +You can paste this into a raw transaction decoder like [this one](https://live.blockcypher.com/btc/decodetx/) and see the data. + +If we were using stacks.js, we would just need to pass this to our function as a buffer like this: + +```javascript +bufferCV(Buffer.from(txRaw, "hex")); +``` + +Where `txRaw` is just a string containing our raw transaction. When we do that, we are presented with the data of the transaction. + +We can then take that data and pull out whatever we need from it. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md new file mode 100644 index 0000000000..571fc20d48 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/post-conditions.md @@ -0,0 +1,136 @@ +--- +title: Post Conditions +description: Working with Stacks post conditions +--- + +The content in this recipe has ben pulled from the [tutorial on post conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). Post conditions are an additional safety feature built into the Stacks chain itself that help to protect end users. + +Rather than being a function of Clarity smart contracts, they are implemented on the client side and meant to be an additional failsafe against malicious contracts. + +Put simply, post conditions are a set of conditions that must be met before a user's transaction will execute. The primary goal behind post conditions is to limit the amount of damage that can be done to a user's assets due to a bug, intentional or otherwise. + +So they are sent as part of the transaction when the user initiates it, meaning we need a frontend library to utilize them. + +Whenever you are transferring an asset (fungible or non-fungible) from one address to another, you should taker advantage of post conditions. + +We're going to use [Stacks.js](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#post-conditions) to familiarize ourselves with them. + +## STX Post Condition + +```js +import { + FungibleConditionCode, + makeStandardSTXPostCondition, + makeContractSTXPostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; + +const standardSTXPostCondition = makeStandardSTXPostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractSTXPostCondition = makeContractSTXPostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount +); +``` + +## Fungible Token Post Condition + +```js +import { + FungibleConditionCode, + createAssetInfo, + makeStandardFungiblePostCondition, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = FungibleConditionCode.GreaterEqual; +const postConditionAmount = 12345n; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const standardFungiblePostCondition = makeStandardFungiblePostCondition( + postConditionAddress, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const fungibleAssetInfo = createAssetInfo(assetAddress, assetContractName); + +const contractFungiblePostCondition = makeContractFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + postConditionAmount, + fungibleAssetInfo +); +``` + +## NFT Post Condition + +```js +import { + NonFungibleConditionCode, + createAssetInfo, + makeStandardNonFungiblePostCondition, + makeContractNonFungiblePostCondition, + bufferCVFromString, +} from "@stacks/transactions"; + +// With a standard principal +const postConditionAddress = "SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE"; +const postConditionCode = NonFungibleConditionCode.Owns; +const assetAddress = "SP62M8MEFH32WGSB7XSF9WJZD7TQB48VQB5ANWSJ"; +const assetContractName = "test-asset-contract"; +const assetName = "test-asset"; +const tokenAssetName = bufferCVFromString("test-token-asset"); +const nonFungibleAssetInfo = createAssetInfo( + assetAddress, + assetContractName, + assetName +); + +const standardNonFungiblePostCondition = makeStandardNonFungiblePostCondition( + postConditionAddress, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); + +// With a contract principal +const contractAddress = "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X"; +const contractName = "test-contract"; + +const contractNonFungiblePostCondition = makeContractNonFungiblePostCondition( + contractAddress, + contractName, + postConditionCode, + nonFungibleAssetInfo, + tokenAssetName +); +``` + +## Sample App + +Here's a [sample application](https://github.com/kenrogers/fabulous-frogs) that utilizes post conditions on the front end to secure user assets. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md new file mode 100644 index 0000000000..fda05f7356 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/sending-bitcoin-with-hiro-wallet.md @@ -0,0 +1,38 @@ +--- +title: Sending Bitcoin with Hiro Wallet +description: Initiate a basic Bitcoin transaction with the Hiro wallet +--- + +Using Hiro's web wallet, we can easily initiate a simple Bitcoin transaction using only a few lines of code. + +You'll need to be authenticated with the Hiro wallet for this to work, with you can see how to do in the [Authentication with Stacks.js](./stacks-js-auth) recipe. + +Once you have the wallet hooked up, you can use the Hiro wallet API to initiate a simple Bitcoin transaction in your JS app like this. + +```javascript +const sendBitcoin = async () => { + const resp = await window.btc?.request("sendTransfer", { + address: "tb1qya9wtp4dyq67ldxz2pyuz40esvgd0cgx9s3pjl", //replace this with whatever address you want to send to + amount: "10000", // the amount you want to send denoted in satoshis + }); + + // Storing txid in local storage + // We'll get back the transaction IF, which we can then use to do whatever we want + if (typeof window !== "undefined") { + localStorage.setItem("txid", JSON.stringify(resp.result.txid)); + } + + // We may want to do something once this transaction has confirmed, so we can set it to pending here and then use an API like mempool.space to query the Bitcoin chain for information about this transaction + localStorage.setItem("txStatus", "pending"); +}; +``` + +Then all we would do is hook up our button to call this `sendBitcoin` function. + +```javascript + +``` + +You can take a look at the [Verifying a transaction on the BTC chain](./verifying-a-btc-tx-was-mined.md) recipe to see a more complex user flow of verifying a transaction was mined using this returned ID as a starting point. + +You can take a look at a bit more info about this simple API on the [Hiro wallet developer docs](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin). diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md new file mode 100644 index 0000000000..89d1f06e00 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/stacks-js-auth.md @@ -0,0 +1,98 @@ +--- +title: Authentication with Stacks.js +description: Authenticating a user with Stacks.js +--- + +Authenticating with a Stacks wallet is a very common task when building Stacks dapps. + +Let's see how to set this up on the front end. + +Code here is pulled from the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +## Stacks.js Code + +We're using React here, but you can modify this for whatever frontend code you are using. + +Before you add the frontend code, you need to install the correct NPM package. + +```bash +yarn add @stacks/connect +``` + +And here's the JS code we'll need to implement. + +```js +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +import { useState, useEffect } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + return ( +
+ +

Hello Stacks

+
+ ); +} + +export default App; +``` + +This is all the code we need to authenticate and access the user data in the UI. + +But how do we actually use it? + +Let's implement a `connectWallet` button to see how we can utilize the data we're pulling here. + +```js +{ + !userData && ( + + ); +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md new file mode 100644 index 0000000000..849c7d1f42 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/stacks-js-sending-transactions.md @@ -0,0 +1,55 @@ +--- +title: Sending Transactions with Stacks.js +description: Sending transactions with Stacks.js +--- + +Any Stacks dapp is going to require sending transaction at some point, so how do we do that? We use the `@stacks/transactions` package. + +Again, this particular snippet is pulled from our [Hello Stacks](../tutorials/hello-stacks.md) tutorial. + +When you send Stacks transactions, don't forget to utilize [post conditions](./post-conditions.md). + +But first, you'll need to install the right NPM package. + +```bash +yarn add @stacks/transactions +``` + +## Stacks.js Frontend Code + +Assuming you are [authenticated](./stacks-js-auth.md), you'll need to import from the `network` package to connect and import the right Clarity values to convert. + +You need to convert values from JS into the right format for Clarity values to ingest. You can view the complete list of types on the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions#constructing-clarity-values). + +```js +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +Let's assume we have a message that we need to send. + +``` +Hello this is something I need to say. +``` + +```js +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +For more details on the different types of transactions you can send, the [Stacks.js docs](https://stacks.js.org/modules/_stacks_transactions) have multiple examples. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md new file mode 100644 index 0000000000..fbbdbd98b4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/cookbook/verifying-a-btc-tx-was-mined.md @@ -0,0 +1,195 @@ +--- +title: Verifying a BTC Transaction was Mined +description: Using Clarity to verify that a Bitcoin transaction was actually mined in the blockchain +--- + +One of the coolest things about Clarity is that it allows us to have visibility into the state of the Bitcoin blockchain. Since Stacks blocks are mined in lockstep with Bitcoin blocks, we can directly read the burnchain header info of each Bitcoin block using Clarity's built-in [`get-burn-block-info?`](https://docs.stacks.co/docs/clarity/language-functions#get-burn-block-info-clarity2) function. + +There are quite a few relatively complex things that need to happen to do this successfully, but a [clarity-bitcoin library](https://github.com/friedger/clarity-bitcoin/) exists to make the process a lot easier and handle some of the heavy lifting for us. + +Let's take a look at how to verify a Bitcoin transaction was mined using Clarity using the library. If you take a look at the `clarity-bitcoin.clar` file in the linked repo, you'll find a function called `was-tx-mined-compact`. That's what we'll be working with, and it looks like this: + +```clarity +(define-read-only (was-tx-mined-compact (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let ((block (unwrap! (parse-block-header header) (err ERR-BAD-HEADER)))) + (was-tx-mined-internal height tx header (get merkle-root block) proof))) +``` + +The transaction itself is relatively simple, but there's a lot happening within other private function calls. I encourage you to read the contract for yourself and trace what is happening, step-by-step, when we call this function. + +For now, we'll just go over how to actually call this function successfully. + +You can see that it takes a few pieces of information: + +- `(height uint)` the block height you are looking to verify the transaction within +- `(tx (buff 1024))` the raw transaction hex of the transaction you are looking to verify +- `(header (buff 80))` the block header of the block +- `(proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})` a merkle proof formatted as a tuple + +:::info + +A Merkle proof is a compact way to prove that a transaction is included in a block in the Bitcoin blockchain. Here's how it works: + +1. Transactions in a block are hashed and paired, then the hashes of the pairs are hashed and paired, and so on until a single hash remains - this is called the Merkle root. +2. The Merkle root is included in the block header. By providing the hashes that lead from a transaction's hash up to the Merkle root, along with the block header, one can prove that the transaction is included in that block. +3. These hashes that connect a transaction to the Merkle root are called the Merkle proof or Merkle path. By providing the Merkle proof along with the transaction hash and block header, anyone can verify that the transaction is part of that block. +4. This allows for efficient decentralized verification of transactions without having to download the entire blockchain. One only needs the transaction hash, Merkle proof, and block header to verify. + +::: + +Once we have this information, we can call into the `clarity-bitcoin.clar` contract and pass in this data. A common practice would be to get this data from a Bitcoin block explorer API like Mempool.space or Blockstream's esplora, parse it into the correct format for this helper, and then pass it to this function. + +We could do that directly via this contract if we just need a direct response on if the transaction was included or not, but more likely we would want to integrate this functionality into a Clarity contract of our own where we can `asserts!` that a transaction was mined before taking another action. + +Here's a basic example where we are calling [Blockstream's API](https://github.com/Blockstream/esplora/blob/master/API.md) using JavaScript, parsing the data into the right format, and then calling into our own `mint` function to only mint an NFT if the selected transaction was mined. + +We can get all the information we need with nothing but the transaction ID, which will usually be passed to us when we use a wallet like [Hiro's web wallet](https://hirowallet.gitbook.io/developers/bitcoin/sign-transactions/sending-bitcoin) to initiate the Bitcoin transaction. + +Let's go through the code we can use to implement this. For full context, this code is taken from the example [bitbadge](https://github.com/kenrogers/bitbadge) repo, which you can take a look at. For a complete ste-by-step walkthrough of how to implement this, check out the [Bitcoin Primer](https://bitcoinprimer.dev). + +Here's the mint function: + +```clarity +(define-public (mint (recipient principal) (height uint) (tx (buff 1024)) (header (buff 80)) (proof { tx-index: uint, hashes: (list 14 (buff 32)), tree-depth: uint})) + (let + ( + (token-id (+ (var-get last-token-id) u1)) + (tx-was-mined (try! (contract-call? .clarity-bitcoin was-tx-mined-compact height tx header proof))) + ) + (asserts! (is-eq tx-sender contract-owner) err-owner-only) + (asserts! (is-eq tx-was-mined true) err-tx-not-mined) + (try! (nft-mint? bitbadge token-id recipient)) + (var-set last-token-id token-id) + (ok token-id) + ) +) +``` + +Note the `(asserts! (is-eq tx-was-mined true) err-tx-not-mined)` line. This is what is doing the heavy lifting. + +:::caution +Right now the clarity-bitcoin library only supports legacy transactions. Work is in-progress to add support for segwit, but until then we have to do a bit of work on the front end to strip the witness data from the raw transaction hex. +::: + +Here's the JavaScript code we can use to get the data we need. + +First we get the raw transaction and the merkle proof (we do this when we first get the transaction ID back). + +The `useEffect` here is so that we can check to see if the transaction was confirmed every 10 seconds before we get the rest of the information. + +```javascript +// Effect hook to check and see if the tx has been confirmed using blockstream API +useEffect(() => { + const intervalId = setInterval(() => { + const txid = JSON.parse(localStorage.getItem("txid")); + if (txid) { + fetch(`https://blockstream.info/testnet/api/tx/${txid}/status`) + .then((response) => response.json()) + .then(async (status) => { + // set txStatus in localStorage if it is confirmed, otherwise we want to leave it pending + if (status.confirmed) { + localStorage.setItem("txStatus", "confirmed"); + // set the block details + const blockDetails = { + block_height: status.block_height, + block_hash: status.block_hash, + }; + setBlockDetails(blockDetails); + localStorage.setItem("blockDetails", JSON.stringify(blockDetails)); + // fetch and set the tx raw + const rawResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/hex` + ); + const txRaw = await rawResponse.text(); + localStorage.setItem("txRaw", txRaw); + // fetch and set the merkle proof + const proofResponse = await fetch( + `https://blockstream.info/testnet/api/tx/${txid}/merkle-proof` + ); + const txMerkleProof = await proofResponse.json(); + localStorage.setItem( + "txMerkleProof", + JSON.stringify(txMerkleProof) + ); + clearInterval(intervalId); + } + }) + .catch((err) => console.error(err)); + } + }, 10000); + return () => clearInterval(intervalId); // Clean up on component unmount +}, []); +``` + +Then we get and parse the rest of the data when we call the actual mint function. + +```javascript +// This function retrieves raw transaction and merkle proof from localStorage and calls the mint Clarity function +const mintBitbadge = async () => { + // Retrieving rawTx and merkleProof from local storage + let txRaw = ""; + let txMerkleProof = ""; + + if (typeof window !== "undefined") { + txRaw = removeWitnessData(localStorage.getItem("txRaw")); + txMerkleProof = JSON.parse(localStorage.getItem("txMerkleProof")); + } + + // First we need to verify that the sender of this transaction is the same as the user that is signed in + if (!verifyCorrectSender()) { + console.log("wrong sender"); + return false; + } + + const blockHeight = blockDetails.block_height; + + // Fetch the block hash + const blockHashResponse = await fetch( + `https://blockstream.info/testnet/api/block-height/${blockHeight}` + ); + const blockHash = await blockHashResponse.text(); + + // Fetch the block header + const blockHeaderResponse = await fetch( + `https://blockstream.info/testnet/api/block/${blockHash}/header` + ); + const blockHeaderHex = await blockHeaderResponse.text(); + + const txIndex = txMerkleProof.pos; + const hashes = txMerkleProof.merkle.map( + (hash) => bufferCV(hexToBytes(hash).reverse()) // lib needs reversed hashes + ); // Convert each hash to BufferCV and reverse it + + const functionArgs = [ + principalCV(userData.profile.stxAddress.testnet), + uintCV(blockHeight), + bufferCV(Buffer.from(txRaw, "hex")), + bufferCV(Buffer.from(blockHeaderHex, "hex")), + tupleCV({ + "tx-index": uintCV(txIndex), + hashes: listCV(hashes), + "tree-depth": uintCV(txMerkleProof.merkle.length), + }), + ]; + + const contractAddress = "ST3QFME3CANQFQNR86TYVKQYCFT7QX4PRXM1V9W6H"; // Replace with your contract address + const contractName = "bitbadge-v3"; // Replace with your contract name + const functionName = "mint"; // Replace with your function name + + const options = { + contractAddress, + contractName, + functionName, + functionArgs, + appDetails: { + name: "BitBadge", + icon: "https://freesvg.org/img/bitcoin.png", + }, + onFinish: (data) => { + console.log(data); + }, + }; + + await openContractCall(options); +}; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md b/i18n/zh/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md index 2dd4b2ca9a..16376c17ee 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/gaia/gaia-on-ec2.md @@ -26,9 +26,10 @@ Use a link in the table to launch the [CloudFormation](https://console.aws.amazo ### Step 2 - Setup stack using template -You need to configure the template with the appropiate values for your hub and domain it runs on. +You need to configure the template with the appropriate values for your hub and domain it runs on. Select `Template is ready` and `Amazon S3 URL` and enter the following Amazon S3 URL: + ``` https://s3-external-1.amazonaws.com/cf-templates-vzldibfi2mw8-us-east-1/2022160J6G-cloudformation.yaml ``` @@ -52,7 +53,7 @@ Specify the stack details and then click `Next`: ![Specify template](/img/cloudf | EmailAddress | _your email address_ | | | GaiaBucketName | _S3 bucket name_ | The template combines this name with the stack name to create a unique S3 bucket. The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. The template combines this name with the stack name to create a unique S3 bucket. The template ignores this field if GaiaStorageType is set to `disk`. | | GaiaStorageType | `s3` or `disk` | Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Select the GaiaStorageType of which to use as a backend for the Gaia Hub. Selecting `s3` causes the template to create an S3 bucket based on the name given in the previous field. Selecting `disk` causes the template to attach a separate EBS volume to the EC2 instance for Hub storage. | -| InstaceType | t2.micro | Select the instance type you want. Select the instance type you want. Default value is `t2.micro`. Select the instance type you want. Default value is `t2.micro`. | +| InstanceType | t2.micro | Select the instance type you want. Select the instance type you want. Default value is `t2.micro`. Select the instance type you want. Default value is `t2.micro`. | | KeyName | | In the KeyName drop-down, select an [EC2 KeyPair](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#KeyPairs:) to enable SSH access to the EC2 instance. You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) You should download the `.pem` keyfile for this pair from the EC2 console. For more information see the [EC2 key pair documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#prepare-key-pair) | | SSHLocation | 0.0.0.0/0 | Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. Leave the SSHLocation field with the default value of `0.0.0.0/0` to enable SSH access from any IP address. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. If you wish to restrict SSH access to the EC2 instance to a certain IP, you can update this field. | | SubnetId | _subnetid_ | Select a public subnet | @@ -93,7 +94,9 @@ ssh -i admin@ Open Your VPCs Select your VPC connected to your Gaia Hub Click `Actions` -> `Edit DNS Hostnames` -> Change `DNS hostnames` to `Enable` + ::: + ## Graphical representation of the cloudformation template -![](/img/cloudformation-gaia-template1-designer.png) \ No newline at end of file +![](/img/cloudformation-gaia-template1-designer.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/gaia/gaia.md b/i18n/zh/docusaurus-plugin-content-docs/current/gaia/gaia.md index 5718b504f2..05d446cccd 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/gaia/gaia.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/gaia/gaia.md @@ -1,14 +1,20 @@ --- title: Gaia description: Decentralized storage architecture for off-chain data -sidebar_position: 5 +sidebar_position: 6 tags: - gaia --- ## Introduction -Apps built with the Stacks blockchain store off-chain data using a storage system called Gaia. +Apps built with the Stacks blockchain can store off-chain data using a storage system called Gaia. + +Gaia is a unique approach to decentralized storage that focuses primarily on user-ownership of data, rather than immutable on-chain storage. The emphasis here is on user control. + +While on-chain storage solutions like IPFS and Arweave are designed for immutable, censorship-resistant permanent storage, they cannot be deemed as providing user control of the data since the user cannot modify or remove the data once it has been deployed. + +Gaia solves a different problem of allowing users to be in control of where their data is stored while connecting the access of that data to their on-chain Stacks identity. Whereas public transactional metadata is best stored on the Stacks blockchain, user application data can often be stored more efficiently and privately in Gaia storage. @@ -38,7 +44,7 @@ The Stacks blockchain stores only identity data. Data created by the actions of A Gaia hub runs as a service which writes to data storage. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. The storage itself is a simple key-value store. The hub service writes to data storage by requiring a valid authentication token from a requestor. Typically, the hub service runs on a compute resource and the storage itself on separate, dedicated storage resource. Typically, both resources belong to the same cloud computing provider. -![Gaiastorage](/img/gaia-storage.png) +![Gai storage](/img/gaia-storage.png) Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. Moreover, Gaia defines a uniform API for applications to access that data. Users can choose a Gaia hub provider. Gaia's approach to decentralization focuses on user control of data and its storage. Users can choose a Gaia hub provider. If a user can choose which Gaia hub provider to use, then that choice is all the decentralization required to enable user-controlled applications. Moreover, Gaia defines a uniform API for applications to access that data. Moreover, Gaia defines a uniform API for applications to access that data. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/gaia/setup-linux.md b/i18n/zh/docusaurus-plugin-content-docs/current/gaia/setup-linux.md index dea034dd65..0d4b1db45d 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/gaia/setup-linux.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/gaia/setup-linux.md @@ -1,6 +1,6 @@ --- title: Linux -description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. +description: Steps to setup a GAIA hub on a Linux server (fresh install). This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. This example is using Debian, but should work on any Linux distribution. It uses docker compose in the backgroud. This example is using Debian, but should work on any Linux distribution. It uses docker compose in the background. tags: - tutorial - gaia @@ -19,8 +19,7 @@ This configuration will setup the following 4 docker containers: apt update && apt upgrade -y && apt install -y git vim gnupg jq ``` -**2. **2. **2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. -For our example we install _docker_ with:

+**2. Install [docker](https://docs.docker.com/engine/install/debian/) and [docker-compose](https://docs.docker.com/compose/cli-command/#install-on-linux)** in your OS. For our example we install _docker_ with: ```bash curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg @@ -48,8 +47,7 @@ chmod +x ${DESTINATION_DC}/docker-compose git clone https://github.com/stacks-network/gaia.git && cd gaia/deploy/docker ``` -**4. **4. Copy and edit appropiate .env file**. -In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. In this example we will store the data localy so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly.

+**4. Copy and edit appropriate .env file**. In the folder `./deploy/docker/` they are different sample files for different configurations like using aws, azure or disk among others. In this example we will store the data locally so we will copy the _disk_ file and update the domain and email fields. Please change `gaia.site.com` and `gaiarocks@mydomain.com` accordingly. Note you need both for the SSL certificate to be created correctly. ```bash export MYGAIADOMAIN=gaia.site.com diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/glossary/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/glossary/index.md new file mode 100644 index 0000000000..419c0e0d73 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/glossary/index.md @@ -0,0 +1,284 @@ +--- +title: Glossary +description: A comprehensive list of terms used within the ecosystem. +--- + +A comprehensive list of terms used within the ecosystem. + +#### App Review + +An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. + +#### Atlas + +A peer network provide a global index for discovery. + +#### Bitcoin (BTC) address + +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. + +#### block + +A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. + +#### blockchain + +A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. + +#### Blockchain Name System (BNS) + +Replacement for DNS. More info [here](../clarity/noteworthy-contracts/bns-contract). + +#### Blockstack Browser + +A deprecated application for accessing identity and storage. + +#### Blockstack Owner Address + +Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShUnHRrMyU6yKtoHEUPhKULs` + +#### Burning + +Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. + +#### consensus hash + +A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. + +#### Consensus rules + +"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. + +#### control plane + +The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. + +#### core node + +A server that runs Stacks Blockchain services. + +#### crypto-asset + +A digital asset which utilizes cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. + +#### cryptography + +The practice and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptographic system. + +#### DAO + +See Decentralized Autonomous Organization. + +#### decentralized application (DApp) + +A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" + +#### Decentralized Autonomous Organization + +A type of contract or suite of contracts on the blockchain that is intended to codify, enforce or automate the processes of an organization. + +#### digital asset + +Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. + +#### digital fingerprint + +A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. + +#### digital signature + +A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. + +#### distributed hash tables (DHT) + +A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. + +#### ephemeral key + +A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. + +#### fork + +The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. + +#### Gaia + +Decentralized storage architecture for off-chain data. More info [here](../gaia). + +#### genesis block + +The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. + +#### id.blockstack + +An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" + +#### Identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. + +#### Know your customer (KYC) + +KYC is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### identity management (IDM) + +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". + +#### know your customer (KYC) + +Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. + +#### light clients + +Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. + +#### magic recovery code + +A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: + +![](/img/qr-code.png) + +#### mesh network + +A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. + +#### mining + +Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. + +#### mining power + +A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. + +#### mining rewards + +Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. + +#### name + +An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. + +#### network operation + +A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. + +#### NFT + +Non fungible token. + +#### Private key + +Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: + +![](/img/private.png) + +The exact format of the public and private key depend on the software you use to create them. + +#### proof-of-burn mining + +The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. + +#### proof-of-work + +A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. + +#### public key + +Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` + +The exact format of the public and private key depend on the software you use to create them. + +#### Public Key Infrastructure (PKI) + +A system which returns a cryptographic public key associated with a name. + +#### replicated state machines (RSMs) + +This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" + +#### Secret recovery Key, + +Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` + +#### seed phrase + +Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word _and its position the sequence_ are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. + +#### smart contract + +A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. + +#### soft fork + +A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. + +#### Stacks (STX) address + +A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the _wallet address_. You access a software wallet with a _seed phrase_. " + +#### Stacks blockchain + +The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. + +#### Stacks Explorer + +An application that allow you to view and search transactions in the blockchain. For example, https://explorer.stacks.co. + +#### Stacks node + +A complete version of our open-source software available on Github at https://github.com/stacks-network/stacks-blockchain/ that governs the creation of the blockchain, the smart contracts that may be written to our blockchain, and other systems that make up the Stacks network, when run on the systems and devices of our users and developers. + +#### Stacks wallet + +An application for accessing assets, identity and storage. + +Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). + +#### storage hub + +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. + +#### storage provider + +A third-party company cloud or software provider that hosts one or more Gaia storage hubs. + +#### transaction + +A transaction is a unit of work within a block. + +#### transaction fee + +Fees paid by participants in a transaction to miners. + +#### two-sided market problem + +Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. + +#### username + +A shorthand name for your id.blockstack. + +#### virtual blockchain + +A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. + +#### wallet address + +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. + +#### watch-only wallet + +A wallet without send and receive ability. You can view only balances and transaction history. + +#### web of trust mining + +Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. + +#### web3 + +The exact definition is still under discussion, but it general refers to the 3rd generation of the web that is based on blockchain technology and incorporates decentralized and token-based economics. + +#### zone file + +A Domain Name System (DNS) zone file is a text file that describes a DNS zone. A DNS zone is a subset, often a single domain, of the hierarchical domain name structure of the DNS. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/intro.md b/i18n/zh/docusaurus-plugin-content-docs/current/intro.md index 84f1eaa649..f284f060c8 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/intro.md @@ -1,12 +1,70 @@ --- -sidebar_label: "Home" +sidebar_label: "Start Here" sidebar_position: 1 --- -# Stacks Docs Introduction +# Stacks Docs -Welcome to the community driven official Stacks Documentation. +**Stacks is Bitcoin L2 that brings smart contract functionality to Bitcoin, without modifying Bitcoin itself.** -Learn about Stacks mining, the STX token, and the Clarity smart contract language. +These docs serve as: -![](/img/Bitcoinet-L_2.svg) +1. An introduction to Stacks (what it is, why you should care, how to build Bitcoin apps with it), +2. A reference guide to various aspects of the Stacks ecosystem +3. A collection of tutorials and code samples to help you learn and build + +If you see something you think you might want to contribute, [please do so](/docs/contribute)! We are always looking for good contributions from the community. + +:::note +Stacks is currently in the middle of a major upgrade called the Nakamoto Release. The next section is dedicated to describing how Nakamoto works and the benefits it brings. + +Keep in mind that other sections of this documentation apply to the pre-Nakamoto version of Stacks, and will be updated when it is released. +::: + +## Nakamoto + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. Nakamoto is designed to make Stacks a true Bitcoin L2 and further unlock the decentralized Bitcoin economy. + +[Learn More About Nakamoto](/docs/nakamoto) + +## Tutorials + +Looking to understand how to build full-stack Bitcoin dapps with Stacks? These tutorials will give you a solid introduction. At the moment we have an intro tutorial and a collection of community-created tutorials focusing on Stacks and Clarity specifically, with a comprehensive deep-dive tutorial series covering Bitcoin-first development on the way. + +[View Hello Stacks Tutorial](/docs/tutorials/hello-stacks) + +## Stacks Academy + +If you are looking to understand Stacks and what it's all about at a deeper level, Stacks Academy is the place to go. + +[Start Stacks Academy](/docs/stacks-academy) + +## Clarity Reference + +Clarity is the language that powers smart contracts built on Stacks. You'll be introduced to Clarity in Stacks Academy, but this section of the docs is where you can find the references for all the keywords and functions in Clarity. + +[View Clarity Reference](/docs/clarity) + +## Nodes and Miners + +Interested in mining or running a Stacks node? This section is where you'll learn what that looks like and how to set it up. + +[View Nodes and Miners](/docs/nodes-and-miners) + +## Gaia + +Gaia is a unique approach to off-chain data storage that focuses on user-ownership of data with access connected to a Stacks identity. + +[View Gaia Docs](/docs/gaia) + +## Cookbook + +The Cookbook is a WIP, but you can check out what we have available now. This is designed to be a collection of code snippets, mini tutorials, and sample projects designed to help you accomplish specific things with Stacks. + +[View Cookbook](/docs/cookbook) + +## Next Steps + +Apply for a grant, get a job, start a company, join an immersive education experience like Clarity Universe. This section will point you to the different places in the Stacks community you can launch and grow your career as a Stacks developer. + +[Grow Your Skills and Career](/docs/next-steps) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md new file mode 100644 index 0000000000..46c768ce69 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/bitcoin-mev-mitigation.md @@ -0,0 +1,62 @@ +--- +title: Bitcoin MEV Mitigation +description: How Nakamoto mitigates Bitcoin MEV +sidebar_label: Bitcoin MEV Mitigation +sidebar_position: 4 +--- + +Miner Extractable Value (MEV) has been a longstanding issue across many blockchains, including Stacks pre-Nakamoto. + +MEV refers to the potential profit miners can extract from the manipulation of transaction inclusion and ordering within the blocks they produce, which can lead to unfair practices and diminished trust in the network. + +Specifically in pre-Nakamoto releases of Stacks, Bitcoin miners with a significant percentage of Bitcoin’s hashrate had the ability to censor commitment transactions of other Stacks miners ensuring they were able to win the block rewards and fees of Stacks blocks where they were also the winner of the Bitcoin block as a Bitcoin miner. + +This allowed them to sometimes win these rewards for minimal bitcoin cost in PoX. This has led to reduction in Stacker BTC rewards and other bad incentives for Stacks mining. As such Nakamoto has changed the approach to sortitions to promote better fairness in the mining process. + +## Sortition Probability Factors + +With the Nakamoto release, Stacks introduces a series of countermeasures to mitigate the influence of MEV and promote a fairer mining landscape. + +- Miner Participation in Recent Blocks: The update emphasizes a miner's consistent participation within the network, requiring a history of attempts in recent blocks (the last 10) to qualify for sortition. This persistent involvement in at least the last 10 blocks aims to foster a dedicated and stable miner community. +- Median of Past Bids Method: By calculating the winning probability based on the median total BTC bids of the last ten blocks, the system discourages aberrant bidding behavior. This reduces the likelihood of a miner skewing sortition chances through atypical or extreme bids. +- Absolute Bid Total: Inclusion of an absolute measure of bids further strengthens the system's robustness. Rather than having a variable determined by just the immediate mining environment, the absolute bid total keeps the process anchored to a broader and more stable economic baseline. + +These changes ensure that miners are rewarded for their genuine contributions to the network's security and continuity, safeguarding the blockchain from manipulation and encouraging a more equitable distribution of rewards. + +## MEV Mitigation Details + +The Nakamoto system uses a variation of the Assumed Total Commitment with Carryforward (ATC-C) MEV mitigation strategy described in [this document](https://forum.stacks.org/uploads/short-url/bqIX4EQ5Wgf2PH4UtiZHZBqJvYE.pdf) to allocate block rewards to miners. Unlike pre-Nakamoto Stacks, there is no 40/60 fee split between two consecutive miners. + +Each miner nominally receives the entire coinbase and transaction fees before the MEV mitigation is applied. + +In the ATC-C algorithm, Nakamoto uses the document's recommended assumed total commitment function: the median total PoX spend across all miners for the past ten Bitcoin blocks. + +It also uses the document's recommended carryforward function for missed sortitions' coinbases: the coinbase for a Bitcoin block without a sortition would be available to winning miners across the next ten tenures. That is, if a miner whose tenure begins during the next ten tenure-changes manages to produce a Stacks block with a Coinbase, then they receive a 10% of the coinbase that was lost. + +The reason ATC (and ATC-C) were not considered as viable anti-MEV strategies before is because a decrease in the PoX total spend can lead to a Bitcoin block with no sortition. This is a deliberate design choice in ATC-C, because it has the effect of lowering the expected return of MEV mining. + +In ATC-C, the probability of a miner winning a sortition is equal to (i.e. no longer proportional to) the miner's BTC spend, divided by the maximum of either the assumed total commit (median total BTC spend in the last 10 blocks) or the total BTC spend in this Bitcoin block. This means that the sum of each miners' winning probabilities is not guaranteed to be 1. The system deals with this by creating a virtual "null" miner that participates in each sortition, such that its probability of the null miner winning is 1 - sum(probabilities-of-all-other-miners). If the null miner wins, then the sortition is treated as empty. + +While the existence of a null miner was a liveness concern in pre-Nakamoto Stacks, it is not a concern in Nakamoto. If the null miner wins tenure N, then the last non-null miner continues to produce blocks in tenure N. They receive transaction fees, but no coinbase for tenure N. + +Nakamoto includes one additional change to ATC-C as described in the above report: if a miner does not mine in at least five of the ten prior Bitcoin blocks, it has zero chance of winning. This requires a Bitcoin MEV miner to participate as an honest miner for the majority of blocks it produces, such that even if they pay the bare minimum PoX payout each time, they are still paying Bitcoin transaction fees to other miners. + +## Example + +The need for this additional tweak becomes apparent when considering the consequences for a real Bitcoin MEV miner who was active in pre-Nakamoto Stacks: F2Pool. + +Consider what happens to F2Pool, who spends 200 sats on PoX and zero sats on transaction fees for their block-commit. Suppose the median total BTC spend over the last ten Bitcoin blocks was 500,000 sats (about what it is at the time of this writing). + +With ATC-C alone, their probability of winning the sortition would be 200 / max(500,000, 200), or about 0.04% chance. The miner would need to send 2,500 such block-commits before winning a Stacks coinbase (worth about 500 USD). + +F2Pool had 13.89% of Bitcoin's mining power over the past three months, so it would take them about 4 months to win a single STX coinbase (which is a very long time horizon). Right now, it costs 22 sats/vbyte to get a Bitcoin transaction mined in the next Bitcoin block; this is what Stacks miners pay. + +A block-commit tx is about 250 vbytes, so that's 5500 sats, or about 1.41 USD with today's BTC price. So, F2Pool would lose money by MEV mining at their current rate if prices stay the same over those 4 months -- they'd forfeit about 3,525 USD in Bitcoin transaction fees (lost by excluding other Bitcoin transactions in order to include their block-commit) for a Stacks coinbase worth 500 USD. They'd have to pay about 1410 sats per block-commit just to break even, and they'd only recoup their investment on average once every 4 months. + +This by itself is not a significant improvement -- F2Pool would be required to go from paying 200 sats to 1410 sats. However, with this proposal's tweek, F2Pool would be required to additionally win five Bitcoin blocks in a row in order to mine this cheaply. + +Given that they have 13.89% of the mining power today, the odds of this happening by chance are only 0.005%. Since this is unlikely -- about once every 20,000 Bitcoin blocks (once every 138.9 days) -- F2Pool would instead be required to send legitimate block-commit transactions in at least 50% of the Bitcoin blocks. + +In 87.11% of those, they would be paying the same transaction fees as every other Stacks miner. This alone would cost them $106.13 USD/day. With the additional de minimis PoX payout, this rises to $212.25 USD/day. In other words, they would expect to pay $29,481.51 USD just to be able to mine one Stacks block for a de minimis PoX payout. This is more expensive than mining honestly! + +If the largest Bitcoin mining pool -- Foundry USA, at 30% of the Bitcoin mining power -- wanted to become a Bitcoin MEV miner on Stacks, then the given parameter choice still renders this unprofitable. There is a 0.243% chance that they win five blocks in a row, and can thus mine a de-minimis block-commit and be guaranteed to win. This happens about once every 2.85 days (every 411.5 Bitcoin blocks), so they'd be spending about $604.91 USD just to mine one Stacks block for free (which is not profitable either). diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/block-production.md b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/block-production.md new file mode 100644 index 0000000000..2137f2b4b6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/block-production.md @@ -0,0 +1,48 @@ +--- +title: Block Production +description: How blocks are produced in Nakamoto and how this unlocks fast blocks and Bitcoin finality +sidebar_label: Block Production +sidebar_position: 2 +--- + +One of the most significant changes coming in Nakamoto is how new blocks are produced. Historically, because Stacks blocks have been anchored 1:1 to Bitcoin blocks, slow block times and transaction times have been one of the biggest pain points for Stacks users and developers. + +Nakamoto brings significantly faster block times by decoupling Stacks block production from Bitcoin block production. In Nakamoto, new Stacks blocks are produced roughly every 5 seconds. + +## Tenure-Based Block Production + +This is achieved via the use of tenure-based block production. Each Bitcoin block introduces a new tenure, in which a single miner cryptographically selected for that tenure is responsible for producing all Stacks blocks. + +But if a single miner is only cryptographically selected for their tenure, and not their produced blocks, what mechanisms exist to ensure the validity of their block production. + +## Stackers + +This is where Stackers come in. In pre-Nakamoto Stacks, Stackers were responsible only for locking their STX tokens to contribute to the economic security of the network. + +In Nakamoto, Stackers are responsible for validating and approving each block produced during a miner's tenure. + +To ensure network consistency, the Stacks protocol commits to the state of the Stacks blockchain with each new Bitcoin block by referencing the first Stacks block produced in the previous tenure. Such a design reinforces the fidelity of transaction data and the synchronization between the two chains. It also links the Stacker’s actions with the actions of miners producing a partnership between the two to create both fast and secure blocks. + +As part of this tenure change, Stackers also agree on a last signed block and require the next miner to build off of this, which prevents new Stacks forks. Stacks does not fork on its own and automatically forks with Bitcoin. + +This symbiotic relationship between Stackers and miners is what creates the capability for both fast blocks and 100% Bitcoin finality. + +This elegant design creates a cooperative relationship between miners and stackers while achieving the best of both worlds with block production and transaction speed and security. + +## Bitcoin Finality + +Speaking of security, the concept of 100% Bitcoin finality is crucial to the design of Stacks. This is what turns Stacks into a true Bitcoin L2 and allows it to leverage all of the security inherent in Bitcoin. + +Let's first define what we mean by 100% Bitcoin finality, then we'll dig into how Nakamoto accomplishes this. + +Finality refers to the point at which transactions are irreversible. Once a blockchain reaches finality, it is nearly impossible to change the ledger's history without undertaking extraordinary measures that are often computationally and economically prohibitive. + +When we talk about Stacks blocks having 100% Bitcoin finality, we mean that they are as hard to reverse as Bitcoin transactions themselves. + +That's a bold claim, so how does Stacks accomplish that? + +As discussed above, miners are responsible for producing Stacks blocks in their tenure, which corresponds to a single Bitcoin block. As part of their block commit transaction, which is the transaction that commits the hash of the Stacks blocks to the Bitcoin chain, miners will also be required to add an indexed block hash. + +Stacks miners are required to commit the indexed block hash of the first block produced by the last Stacks miner in their block-commit transactions on Bitcoin. This is the SHA512/256 hash of both the consensus hash of all previously-accepted Bitcoin transactions that Stacks recognizes, as well as the hash of the block itself. + +This will anchor the Stacks chain history to Bitcoin up to the start of the previous miner's tenure, as well as all causally-dependent Bitcoin state that Stacks has processed. This ensures Bitcoin finality, resolves miner connectivity issues by putting fork prevention on stackers, and allows nodes with up-to-date copies of the Stacks chain state to identify which Stacks blocks are affected by a Bitcoin reorg and recover the affected Stacks transactions. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md new file mode 100644 index 0000000000..ecf28e3e90 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/clarity-wasm.md @@ -0,0 +1,7 @@ +--- +title: Clarity WASM +description: The new Clarity WASM runtime +sidebar_label: Clarity WASM +sidebar_position: 5 +draft: true +--- diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/index.md new file mode 100644 index 0000000000..75c7e53007 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/index.md @@ -0,0 +1,28 @@ +--- +title: Nakamoto +description: Overview of the Nakamoto release and how to use it +sidebar_label: Nakamoto +sidebar_position: 2 +--- + +The Nakamoto Release is an upcoming hard fork on the Stacks network designed to bring several benefits, chief among them are increased transaction throughput and 100% Bitcoin finality. + +The Nakamoto release brings many new capabilities and improvements to the Stacks blockchain by focusing on a set of core advancements: improving transaction speed, enhancing finality guarantees for transactions, mitigating Bitcoin miner MEV (miner extractable value) opportunities that affect PoX, and boosting robustness against chain reorganizations. + +This portion of the documentation is broken up into several sections. + +## How Nakamoto Works + +If you are interested in learning more about how Nakamoto works, you can continue on in the following pages where we'll cover each component of Nakamoto. + +## Controlled Testnet + +Neon is the currently released controlled testnet that is available for us. It actually comes with two testnets, one which uses the new ClarityWASM VM (one of the components of Nakamoto) and one that uses the current Clarity VM. + +Argon is the next testnet to be released, slated for late February. + +Neon is available to be used now, get more details on the [Neon docs page](/docs/nakamoto/neon). + +Expect frequent changes to the testnets as it will be upgraded quite often. + +You can track the work being done on Nakamoto [on GitHub](https://github.com/stacks-network/stacks-core/milestones?direction=asc\&sort=title\&state=open). diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/neon.md b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/neon.md new file mode 100644 index 0000000000..5305b8eab1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/neon.md @@ -0,0 +1,32 @@ +--- +title: Neon +description: How to get started with the Neon Nakamoto testnet +sidebar_label: Neon +sidebar_position: 6 +--- + +Neon is the first controlled testnet release for Nakamoto and ships with two separate testnets, one with the previous Clarity VM and one with the upcoming Clarity WASM. + +The primary purpose of these testnets is is performance benchmarking with the new consensus rules. + +Both testnets allow users and developers to view and interact with Nakamoto block production, meaning each testnet has Nakamoto coinbase transactions, testable VRF, tenure change transactions, and multiple Stacks blocks per Bitcoin block. + +Both testnets utilize Bitcoin Regtest and utilize a single miner, this is what is meant by "controlled" testnet. These testnets are producing blocks roughly every 5 seconds, which you can see reflected in the explorer. + +If non of that makes any sense, be sure to check out the previous pages of this Nakamoto section. + +Both testnets ship with functioning APIs and explorers to experiment with + +## Controlled Testnet 1 (Clarity VM) + +- [API](https://api.nakamoto-1.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-1.hiro.so) + +## Controlled Testnet 2 (Clarity WASM) + +- [API](https://api.nakamoto-2.hiro.so/extended/v1/status) +- [Explorer](https://explorer.hiro.so/blocks?chain=testnet\&api=https://api.nakamoto-2.hiro.so) + +You can also use this [preview version of Clarinet](https://github.com/hirosystems/clarinet/releases/tag/nakamoto-preview-1) in order to test Clarity WASM in your local Devnet. + +Further documentation on API endpoints and Stacks.js functions is forthcoming. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/signer.md b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/signer.md new file mode 100644 index 0000000000..519e271d08 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/signer.md @@ -0,0 +1,149 @@ +--- +title: Running a Signer +description: How to run a Stacks signer +sidebar_label: Running a Signer +sidebar_position: 4 +--- + +:::warning +This document intends to lay out all the steps required to run a signer on testnet after the “Argon” milestone is reached and deployed to testnet. Much of this will not work today, but is being included so that interested parties can familiarize themselves with the process as it will work after the Argon release. Argon is still in development and these instructions will change. +::: + +## Step by Step Instructions + +### 1. Generate TOML file + +Create a TOML file (`signers.toml`) with the following content: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +``` + +### 2. Generate Keys + +You’ll need two private keys: + +`stacks_private_key`: the private key that corresponds to the public key that will be registered in the StackerDB +`message_private_key`: the key used when signing messages for block proposals and other messages. + +One way to generate a private key is using the `@stacks/cli` package. With node.js installed, run in the command line: + +`npx –yes @stacks/cli@latest make_keychain` + +You’ll see output like this: + +```json +{ + "mnemonic": "tilt invite caught shoe shed gravity guitar bench spot dial garlic cushion gate garlic need often boss spoon under fence used across tip use", + "keyInfo": { + "privateKey": "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601", + "publicKey": "0396152c9c1ba3edce6d708d9b652916a4a8320f3a4a5f44c7b1142002cf87882f", + "address": "SP2R765DGGBJRAEJD368QDWS471NRY4D566XKTSY8", + "btcAddress": "1H5ynzN1D9FPV7wknsAHR7RhoX1YBEoSy9", + "wif": "L19veovqpwzNgVgzY45ETu8nSMc8vp21vVjbHNdDN85KnUAEEKQX", + "index": 0 + } +} +``` + +Save the output somewhere. + +Take the `privateKey` property from that and add it to your `signer.toml` with the property \`stacks_private_key. + +e.g. `stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601"` + +Next, we need to add the `message_private_key`. You can choose to reuse your Stacks private key or generate a new one. + +The `message_private_key` needs to be base58 encoded. You can use [this tool](https://appdevtools.com/base58-encoder-decoder) to encode the private key as base58. + +In the base58 encoding tool, paste in your `stacks_private_key` and set "Treat input as Hex". Make sure you delete the 01 at the end or the signer will throw an error. + +Take the output and add it to your signer.toml file: + +`message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy"` + +The config file should now look like this, but with different private keys: + +```toml +node_host = "127.0.0.1:20443" +endpoint = "127.0.0.1:30000" +network = "testnet" +stacks_private_key = "7567052905c21867fff273f5c018fb254a282499008d7e8181935a1a1855cb0601" +message_private_key = "8uHp7CVqu8JWiPzW5g7FX2ZthwCKzyxVK9DfjiYjUkiy" +``` + +:::note +At the moment, there are 3 other fields that need to be included, but those will be removed by the Argon release. Prior to argon, add this to the end of the config file if you want to run the signer: + +```toml +stackerdb_contract_id = "ST11Z60137Y96MF89K1KKRTA3CR6B25WY1Y931668.signers-stackerdb" +signer_id = 0 +signers = [ + {public_key = "swBaKxfzs4pQne7spxhrkF6AtB34WEcreAkJ8mPcqx3t", key_ids = [1, 2, 3, 4]}, + {public_key = "yDJhntuJczbss1XGDmyWtG9Wpw5NDqoBBnedxmyhKiFN", key_ids = [5, 6, 7, 8]}, + {public_key = "xNVCph6zd7HLLJcuwrWz1gNbFoPHjXxn7cyRvvTYhP3U", key_ids = [9, 10, 11, 12]}, + {public_key = "p2wFfLEbwGCmxCR5eGa46Ct6i3BVjFrvBixRn7FnCQjA", key_ids = [13, 14, 15, 16]}, + {public_key = "26jpUNnJPvzDJRJg3hfBn5s5MR4eQ4LLTokjrSDzByh4i", key_ids = [17, 18, 19, 20]} +] +``` + +::: + +### 3. Run the signer + +We don't yet have Docker images that include the stacks-signer binary, so in the meantime you'll build from source. [This pull request](https://github.com/stacks-network/stacks-core/pull/4268) changes our CI to include the stacks-signer binary in Docker builds. + +The signer will need to store state via disk, but that code is not yet built. Documentation will be created when it is more defined. + +Follow [these instructions](https://github.com/stacks-network/stacks-core?tab=readme-ov-file#building) for building the stacks-core repository from source. + +Once you've run `cargo build`, go back to the folder with your `signer.toml` file and run: + +```bash +# replace with the location of your `stacks-core` folder: +_STACKS_CORE_FOLDER_/target/debug/stacks-signer start --config signer.toml +``` + +You should see output that looks like this: + +```bash +Signer spawned successfully. Waiting for messages to process... +INFO [1705699009.844671] [stacks-signer/src/runloop.rs:438] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized +``` + +:::note +[This PR](https://github.com/stacks-network/stacks-core/pull/4280) adds a /status endpoint to the signer. Once the signer is running, the client should check this endpoint to ensure it is running and listening correctly. +::: + +## Production environment for Signer + +Running the signer in production requires two things: + +- A machine for running a Docker image +- A volume for storing state + +The Docker image needs to use a user-provided config file, which is used when running the signer. Depending on the production environment, there are typically two ways to do this: + +Use the default published image, which expects you to include the config file somewhere on disk +Create your own Dockerfile, which is a simple wrapper around the official image + +An example wrapper Dockerfile (this doesn’t work today!): + +```DOCKERFILE +FROM blockstack/stacks-core + +RUN mkdir -p /config + +COPY signer.toml /config/signer.toml + +CMD ["stacks-signer", "run", "--config", "/config/signer.toml"] +``` + +## System Requirements to Run a Signer + +https\://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md +https\://github.com/stacksfoundation/miner-docs/blob/main/scripts/install_stacks.sh + +Minimum Requirements: run a full node, run the signer binary. 1 cpu, 4gb of ram, 150GB of storage as a minimum. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/stacking.md b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/stacking.md new file mode 100644 index 0000000000..4c5c22f647 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nakamoto/stacking.md @@ -0,0 +1,174 @@ +--- +title: Stacking Flows +description: Stacking flows in Nakamoto +sidebar_label: Stacking Flows +sidebar_position: 5 +--- + +In Nakamoto, stacking flows have significant changes in comparison to previous versions of Stacks. Because Nakamoto requires stackers to run a signer, which validates blocks produced by Stacks miners, stackers need to provide new information when making Stacking transactions. + +These changes affect both solo Stacking and delegated Stacking. This document intends to outline the new flows for both cases, so that we can better understand what Stackers need to do to Stack in Nakamoto. + +## Definitions + +- Stacker: an entity locking their STX to receive PoX rewards. This is a broad term including solo Stackers and Stackers who use pools. +- Solo stacker: an entity that locks their own STX and runs a signer. They don’t receive delegation. +- Delegator: a stacker who locks their STX and delegates to a signer. They don’t run the signer. +- Delegatee: an entity that runs a Signer and allows others to delegate their STX to them. A delegatee doesn’t need to Stack their own STX, but they can. +- Signer: an entity that runs the stacks-signer software and participates in block validation. This can be either a solo Stacker an entity receiving delegated STX. In many cases we also refer to “signer” as the software that validates blocks. We may want to try and improve this language to be more clear. + +## First, run a signer + +This is a necessary prerequisite to stacking. + +Running a signer involves setting up a hosted production environment that includes both a Stacks Node and the Stacks Signer. For more information, refer to [how to run a signer](./signer.md). + +Once the signer software is running, the signer needs to keep track of the `stacks_private_key` that they used when configuring their signer. This will be used in subsequent Stacking transactions. + +## Signer keys and signer key signatures + +The main difference with Stacking in Nakamoto is that the Signer (either solo Stacker or signer running a pool) needs to include two new parameters in their Stacking transactions: + +1. `signer-key`: the public key that corresponds to the `stacks_private_key` their signer is using +2. `signer-signature`: a signature that demonstrates that this Stacker actually controls their `signer-key`. Because signer keys need to be unique, this is also a safety check to ensure that other Stackers can’t use someone else’s public key. + +## Generating a signer key signature + +The `signer-signature` uses the signer’s Stacks private key and creates a signature over the message (`pox-address`, `reward-cycle`), `where pox-address` is the BTC address used for rewards, and `reward-cycle` is the current reward cycle. + +The exact user experiences for generating the `signer-signature` is to be determined, but there are two high-level processes that can be expected: + +1. Using the stacks-signer or other CLI, via a command like `stacks-signer generate-stacking-signature {pox-address} {reward-cycle}`. +2. Using an application like a wallet or a web app. The signature is designed such that Stackers can use pre-existing standards for signing data with a wallet like [Leather](https://leather.io/) and [XVerse](https://www.xverse.app/). Stackers can also use hardware wallets to create this signature. + +Solo Stackers will likely generate their signature as a first step while making their Stacking transaction. + +### Using a hardware or software wallet to generate signatures + +When the signer is configured with a `stacks_private_key`, the signer may want to be able to use that key in a wallet to make stacking signatures. + +If the signer uses a tool like [@stacks/cli](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (aka “seed phrase”) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path for generating Stacks keys, any Stacks wallet will default to having that same private key when the wallet is imported from a derivation path. Similarly, if a hardware wallet is setup with that mnemonic, then the Signer can use a wallet like Leather to make stacking signatures. + +The workflow for using a setting up a wallet to generate signatures would be: + +1. Use @stacks/cli to generate the keychain and private key. + 1. Typically, when using a hardware wallet, it’s better to generate the mnemonic on the hardware wallet. For this use case, however, the signer software needs the private key, and hardware wallets (by design) don’t allow exporting private keys. +2. Take the `privateKey` from the CLI output and add it to your signer’s configuration. +3. Take the mnemonic (24 words) and either: + 1. Setup a new hardware wallet with this mnemonic + 2. Store it somewhere securely, like a password manager. When the signer needs to generate signatures for Stacking transactions, they can import it into either Leather or XVerse. + +When the user needs to generate signatures: + +1. Setup your wallet with your signer key’s private key. Either: + 1. Setup your Leather wallet with a Ledger hardware wallet + 2. Import your mnemonic into Leather, XVerse, or another Stacks wallet +2. Open an app that has stacking signature functionality built-in +3. Connect your wallet to the app (aka sign in) +4. In the app, enter your PoX address and “submit” +5. The app will popup a window in your wallet that prompts you to sign the information + 1. The app will show clear information about what you’re signing +6. Create the signature + 1. If using a Ledger, confirm on your device +7. The app will display two results: + 1. Your signer key, which is the public key associated with your signer’s key + 2. Your signer signature +8. Finally, make a Stacking transaction using the signer key and signer signature. + +## Solo Stacking + +### Call the function `stack-stx` + +Just like in previous versions of PoX, Stackers call `stack-stx`, but with the new arguments added in Nakamoto. The arguments are: + +- Amount +- PoX Address: the BTC wallet to receive Stacking rewards +- Start burn height: the current BTC block height +- Lock period: the number of cycles to lock for (1 minimum, 12 max) +- Signer key: the public key that their signer is using +- Signer signature: the signature that proves control of this signer key + +### Act as a signer + +In the “prepare phase” before the next stacking cycle (100 blocks), the exact set of Stackers will be selected based on the amount of STX stacked. Just like in previous versions of PoX, each Stacker will have some number of reward slots based on the amount of STX locked. + +It is critical that Stackers have their signer running during this period. The prepare phase is when distributed key generation (DKG) occurs, which is used when validating blocks by signers. + +In general, Stackers don’t need to do anything actively during this period, other than monitoring their Signer to ensure it’s running properly. + +### Extending their stacking period + +Just like in the current version of PoX, Stackers can extend their lock period while still Stacking. The function called is `stack-extend`. + +Stackers can “rotate” their signing key when extending their lock period. + +The arguments are: + +- Extend count: the number of cycles to add to their lock period. The resulting lock period cannot be larger than 12. For example, if currently locked with 6 cycles remaining, the maximum number they can extend is 6. +- Pox Address: the BTC address to receive rewards +- Signer public key: the public key used for signing. This can stay the same, or the Stacker can use a new key. +- Signer signature: a signature proving control of their signing key + +## Delegated stacking + +Similar to the changes to solo Stacking, the big difference for delegation flows is the inclusion of signer keys and signatures. Because signers need to make transactions to “finalize” a delegation, these new arguments add new complexities to the signer. + +### Delegator initiates delegation + +The first step, where the delegator sets up their delegation to a signer, is to call `delegate-stx`. The arguments here are unchanged: + +- Amount +- Delegate to: the STX address of the signer they’re delegating to. Note that this is different from the “signer key” used. Instead, this is the STX address that is used to make PoX transactions. +- Until burn height: an optional argument where the delegation expires +- Pox Address: an option BTC address that, if specified, the signer must use to accept this delegation + +### Signer “activates” the delegation + +Just as in the current PoX contract, the signer calls `delegate-stack-stx` to commit the delegator’s STX. The arguments are: + +- Stacker: the STX address of the delegator +- Amount +- Pox Address +- Start burn height +- Lock period: number of cycles to lock for. If the delegator provided the until burn height argument, then the end of these cycles cannot be past the expiration provided. + +This step also allows the Signer to proactively choose which Stackers they’ll accept delegation from. For “closed” pools, the signer will only call this function for approved Stackers. It is up to each signer who runs a closed pool to implement this process, but tooling will likely be created to make this easier. + +This step can happen for many Stackers before going to the next step. + +### Signer “commits” delegated STX + +At this point, the STX are committed to the signer, and the signer has some “aggregate balance” of committed STX. The signer is not actually eligible for rewards and signer slots until this step is called. + +The signer cannot call this until the total number of STX committed is larger than the minimum threshold required to Stack. This threshold is a function of the total number of liquid STX. At the moment, the threshold is 90,000 STX. + +Once the threshold is reached, the signer calls `stack-aggregation-commit`. This is the point where the signer must provide their signer key and signer key signature. The arguments are: + +- Pox Address +- Reward-cycle: the current reward cycle +- Signer key: the public key of their signer +- Signer signature + +Once this succeeds, the signer is eligible for reward slots. The number of reward slots depends on the amount of STX committed to this signer. Even if the signer commits more than the “global minimum”, the minimum amount to receive a slot depends on the amount of STX locked for each cycle. For example, in the current PoX cycle, that amount is 110,000 STX. + +To act as a signer, each step up to this point must be taken before the prepare phase of the next cycle begins. It is crucial that the signer software is running. + +### Signer increases amount committed + +Even after the signer commits to a certain amount of STX in the previous step, the signer can increase this amount once more delegations are received. The initial steps must be taken for each Stacker (`delegate-stx` and then `delegate-stack-stx`), and then `stack-aggregation-increase` can be called. + +### The need for a separate “Delegate Private Key” + +The concept of the “signer key” or “signer private key” was introduced earlier in this document. The signer key is used during consensus mechanisms to sign blocks in Nakamoto. + +Signers using delegation also need a separate keychain to make Stacking transactions such as `delegate-stack-stx` listed earlier. They need a separate key because they need to have the ability to rotate their signer key when necessary. The PoX contract is designed to support rotating the signer key without needing their Stackers to un-stack and re-stack later. You cannot rotate a delegate key without needing to wait for all delegated Stackers to un-stack and finally re-stack to the new delegate address. + +Because of this limitation of being unable to rotate delegate addresses, it’s highly recommended to have a separate delegate key. The benefit of a separate delegate key is that it can easily be used in existing wallets, including hardware wallets. + +## Tooling for Stackers + +The exact tooling that will be available for both solo and delegated stacking is still in the works, but several options are being explored including: + +- CLI tooling +- Web apps +- BTC native multi-sigs diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/next-steps/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/next-steps/index.md new file mode 100644 index 0000000000..00ddec9178 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/next-steps/index.md @@ -0,0 +1,39 @@ +--- +title: Next Steps +description: A guide to making a living in the Stacks world +sidebar_position: 7 +--- + +# Furthering Your Stacks Skills and Career + +The Stacks ecosystem is rapidly growing, and there are currently multiple ways for interested developers to monetize their hard work and make a living building the next generation of the Internet. + +## Awesome Stacks + +Awesome Stacks is a community-curated collection of resources for learning and building on Stacks. It has tons of helpful developer tools, companies, and learning resources to help you further your Stacks knowledge. + +[Awesome Stacks Repo](https://github.com/friedger/awesome-stacks-chain) + +## Grow Your Skills + +The first step to going pro is to level-up your skills. The best way to do that is through Clarity Universe, a comprehensive Clarity training camp that will take you from Stacks beginner to Clarity smart contract developer. + +[Register for Clarity Universe](https://clarity-lang.org/universe) + +## Stacks Jobs + +Multiple entities in the Stacks world are currently hiring. After you've learned how to build things on Stacks, you can show employers you are available for work and start looking for a full-time role in the Stacks job board. + +[View the Job Board](https://stacks.co/jobs) + +## Grants + +Have an idea for a project that could help the Stacks ecosystem? One of the Stacks Foundation's primary focuses is the grants program, which rewards builders for creating tools that benefit Stacks as a whole. + +[Apply for a Grant](https://stacks.org/grants) + +## Stacks Accelerator + +Interested in starting your own company? Join the Stacks Accelerator to get mentorship and funding to build the next great Stacks company. + +[Join the Accelerator](https://stacks.ac) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md index 99aeac842b..9f84425f21 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/digitalocean.md @@ -1,28 +1,30 @@ --- -title: 数码海洋上的应用 +title: Run a Node with Digital Ocean description: A guide to setup Stacks on DigitalOcean -sidebar_position: 4 +sidebar_position: 2 tags: - tutorial --- ## Introduction -This is a step by step guide to deploy the [Stacks Blockchain on DigitalOcean](https://marketplace.digitalocean.com/apps/stacks-blockchain). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). Code is hosted on this [Github repository](https://github.com/stacks-network/stacks-blockchain-docker). +This is a step by step guide to deploy the [Stacks Blockchain](https://github.com/stacks-network/stacks-blockchain) on [DigitalOcean](https://digitalocean.com). + +Build code is hosted on this [Github repository](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from here](https://github.com/stacks-network/stacks-blockchain-docker) ## Steps #### Step 1 -Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. Click on `Create Stacks Blockchain Droplet`. Click on `Create Stacks Blockchain Droplet`. +Go to the [Stacks Blockchain page](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. Click on `Create Stacks Blockchain Droplet`. Click on `Create Stacks Blockchain Droplet`. ![](/img/sh_digitalocean-marketplace.png) #### Step 2 -Choose a plan (it will only allow you to select a plan that meets the minimum requirements) and your prefered datacenter region. ![](/img/sh_digitalocean-choose-plan.png) +Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. ![](/img/sh_digitalocean-choose-plan.png) #### Step 3 -Enter a root password or enable SSH keys if your prefer. +Enter a root password or [enable SSH keys](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if your prefer. ![](/img/sh_digitalocean-choose-authentication.png) @@ -46,41 +48,48 @@ Congratulations! Congratulations! You are now running the Stacks Blockchain. Con ## Getting started after deploying Stacks Blockchain -Once droplet is launched, initial startup can take several minutes while BNS data is imported (this is a one time operation). +Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can `ssh root@your_droplet_public_ipv4` to the host and run: `/opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs`. -Once the stacks blockchain starts to sync with peers, application ports will open and nginx port 80 will now start proxying requests. +After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: ```json { - "server_version": "stacks-blockchain-api v3.0.3 (master:cd0c8aef)", + "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { - "block_height": 16220, - "block_hash": "0x3123fba9c0de6b569573494cf83c1d5d198a66bfd5f48ef97949b6bf11ba13be", - "index_block_hash": "0xeec960fbbd6186b4ccac85ce12adba72be497d881f81e077305c90955b51a6ae" + "block_height": 91820, + "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", + "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", + "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", + "microblock_sequence": 4 } } ``` +:::tip For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docs](https://docs.hiro.so/api) ::: + All services are managed by a [systemd unit file](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh script](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. -Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/README.md#quickstart). +Full details on how to use the manage.sh script is [available here](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md). -## API Creation +## Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean API](https://digitalocean.com/docs/api). As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. You’ll need to either save your [API access token](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. +:::note _The `name`, `region` and `size` values below are hardcoded, so adjust as desired._ ::: + ```bash -curl -X POST -H 'Content-Type: application/json' \ +$ export TOKEN= +$ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ - '{"name":"choose_a_name","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ + '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" ``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md new file mode 100644 index 0000000000..12d86c7ee2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/hosted-nodes.md @@ -0,0 +1,25 @@ +--- +title: Run a Node with a Hosted Provider +description: A guide to setup Stacks on a hosted provider +sidebar_position: 3 +tags: + - tutorial +--- + +We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples on the current providers that are know to support running a node. + +## Quicknode + +Please refer to the [Quicknode Section](./quicknode) for instructions on launching an instance with Quicknode. + +## Stacks on Render + +The [render-stacks](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Render](https://render.com) service in one click. + +:::note +While it is _possible_ to use the free plan with some modifications, _ ***it is recommended to run this on paid plan*** _ +::: + +## Stacks on Fly + +The [fly-stacks](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Fly](https://fly.io) service. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md index b6cbb9754a..e5f4f2c250 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/index.md @@ -1,11 +1,11 @@ --- title: Nodes and Miners description: Nodes and Miners -sidebar_position: 7 +sidebar_position: 5 --- -Here are all the steps to run nodes and miners, both on mainnet and testnet. +This section will walk through the technical setup steps required to run Stacks Blockchain nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. -## What's a Stacks node? +Running your own Stacks node is a great way to increase the decentralization of the ecosystem and not have to rely on any third-party, centralized providers. -## What's a Stacks miner? +Although it does take some more effort and setup, it's a valuable exercise in understanding how the different pieces of a Stacks Dapp interact with each other. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md index 40397a51e0..dd8ee721cc 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-costs-and-fees.md @@ -8,7 +8,7 @@ sidebar_position: 8 Fee and cost estimators can be configured via the config section `[fee_estimation]`: -``` +```toml [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate @@ -22,3 +22,5 @@ enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs for transactions. Estimators and metrics can be selected using the configuration fields above, though the default values are the only options currently. `log_error` controls whether or not the INFO logger will display information about the cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. Cost estimators are **not** consensus-critical components, but rather can be used by miners to rank transactions in the mempool or client to determine appropriate fee rates for transactions before broadcasting them. The `fuzzed_weighted_median_fee_rate` uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks. Estimates are then randomly "fuzzed" using uniform random fuzz of size up to `fee_rate_fuzzer_fraction` of the base estimate. + +There is also a [mining calculator](https://friedger.id/mining-calculator/) that can help you with this process, with the [source code available here](https://github.com/friedger/mining-calculator). diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md index 751a5f87b7..67ee36c015 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-mainnet.md @@ -1,197 +1,100 @@ --- title: Mine mainnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 mainnet -sidebar_position: 5 +description: Set up and run a miner on Stacks Mainnet +sidebar_position: 6 tags: - tutorial --- ## Introduction -Make sure you've followed the [run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the mainnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you're interested in mining on the testnet, you can find instructions on how to do that [here](miner-testnet): +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining): +If you're interested in mining on the Stacks testnet, you can find instructions on how to do that [here](miner-testnet): -## Running bitcoind locally +## Running a Bitcoin Mainnet Full Node -To participate as a miner on mainnet, you must have access to a mainnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) -Next, start bitcoind with the following configuration: +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) If you want to learn more about the technical details of mining, please review the [mining guide](../stacks-academy/mining): -```toml -server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 -banscore=1 -bind=0.0.0.0:8333 -rpcbind=0.0.0.0:8332 -rpcport=8332 -``` - -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few days for the node to synchronize with the Bitcoin mainnet. - -## Running a miner - -First, a keychain needs to be generated. First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. - -```bash -npx @stacks/cli make_keychain 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: -**Don't lose this information** - we'll need to use the `privateKey` field later on. +### Update the Bitcoin Configuration File -The above BTC address will then need to be imported into the BTC network. +Next, update the bitcoin configuration: -```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - - - -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - - - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). - -Update the following properties: +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml -[node] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... - -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +server=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpassword +rpcallowip=0.0.0.0/0 +bind=0.0.0.0:8333 +rpcbind=0.0.0.0:8332 +dbcache=512 +banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 ``` -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. Replace the `seed` field with your private key. Save and close this configuration file. Replace the `seed` field with your private key. Save and close this configuration file. +### Start Bitcoin -To run your miner, run this in the command line: +Finally, start bitcoin as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): ```bash -stacks-node start --config=./testnet/stacks-node/conf/mainnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. Your node should start. Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. The steps above are great for trying to run a node temporarily. The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: To do so, use the same configuration as above, but run: To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few days for the node to synchronize with Bitcoin mainnet. +::: -The above code will compile an optimized binary. To use it, run: To use it, run: To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ```bash -cd ../.. -cd ../.. -cd ../.. -./target/release/stacks-node start --config=./mainnet-miner-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +getblockchaininfo | jq .blocks +773281 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the mining guide](../understand-stacks/mining). - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: In the command line, run: In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node mainnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a node](run-a-node) and [running bitcoind locally](#running-bitcoind-locally) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get mainnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first we need to generate a keychain. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command. To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command. +First, a keychain needs to be generated. First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -205,169 +108,99 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -The above BTC address will then need to be imported into the BTC network. +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin mainnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: ```bash -bitcoin-cli -rpcport=8332 -rpcuser=your-user -rpcpassword=your-password importaddress +bitcoin-cli \ + -rpcport=8332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress ``` -Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). + + +Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -### Update configuration file + -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +### Update the Stacks Blockchain Configuration File -Update the following properties: +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. -```toml -[node] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Next, update the bitcoin configuration: -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) -[burnchain] -... +```toml [node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" [burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "mainnet" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 8332 +peer_port = 8333 +satoshis_per_byte = 100 +burn_fee_cap = 20000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. Replace the seed field with your private key. Save and close this configuration file. Replace the seed field with your private key. Save and close this configuration file. +### Start the Stacks Blockchain -### Run the miner - -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/mainnet-miner-conf.toml +stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: If so, allow access to run the node. -::: If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - -Your node should start. Your node should start. It will take some time to sync, and then your miner will be running. +Your node should start. Your node should start. Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: In the command line, run: +In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: In the command line, run: In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=mainnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/mainnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the mainnet node with Docker. +Alternatively, you can run a Stacks mainnet miner with Docker. -:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: ::: ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed. ::: -### Generate keychain and get tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some BTC to that address. We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). - -### Update configuration file +We need to get some BTC to that address. We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/mainnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/mainnet-miner-conf.toml). +### Update Stacks Blockchain Docker Configuration File -Update the following properties: +Use the steps oulined above to create the [configuration file](miner-mainnet#update-the-stacks-blockchain-configuration-file) -```toml -[node] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... - -[burnchain] -... -[node] -... -# Enter your private key here -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on mainnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. Replace the seed field with your private key. Save and close this configuration file. - -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: If removed, debug logs will be disabled ::: If removed, debug logs will be disabled ::: @@ -378,7 +211,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd)/testnet/stacks-node/conf/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -393,9 +227,9 @@ docker logs -f stacks_miner ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a mainnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) @@ -404,13 +238,7 @@ Ensure you have the following prerequisites installed on your machine: ### Generate keychain and get some tokens -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null -``` - -We need to get some BTC to that address. We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). We need to get some BTC to that address. You should be able to transfer BTC to this address using a crytpocurrency exchange such as [Coinbase](https://www.coinbase.com), [Binance](https://www.binance.com), or [Kraken](https://www.kraken.com). +Use the steps [outlined above](miner-mainnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md index 7dc2ac76ca..c655e31ba3 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/miner-testnet.md @@ -1,35 +1,52 @@ --- title: Mine testnet Stacks tokens -description: Set up and run a miner on the Stacks 2.0 testnet -sidebar_position: 4 +description: Set up and run a miner on Stacks Testnet +sidebar_position: 5 tags: - tutorial --- ## Introduction -Make sure you've followed the [Run a node](run-a-node) procedure. Once completed it's only a few more steps to run a proof-of-burn miner on the testnet. +For more on the technical details of mining, please review the [mining guide](../stacks-academy/mining) -If you want to learn more about the technical details of mining, please review the [mining guide](../understand-stacks/mining). +The following is an abridged version of the [walkthrough here](https://github.com/stacksfoundation/miner-docs/tree/testnet), written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed ([PR's welcome!](../contribute/docs)). -## Running bitcoind locally +If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that [here](miner-mainnet): -To participate as a miner on Testnet, you must have access to a testnet bitcoin node. One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) One way to accomplish this is to run bitcoind locally. [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements) +## Running a Bitcoin Testnet Full Node -First, download the bitcoind software for your platform from https://bitcoin.org/en/download. +To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. -Next, start bitcoind with the following configuration: +- [Ensure your computer meets the minimum hardware requirements before continuing.](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) + +First, download a [bitcoin binary](https://bitcoin.org/en/download), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) + +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/bitcoin` ::: + +### Update the Bitcoin Configuration File + +Next, update the bitcoin configuration: + +- **optional but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin` +- **optional but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4 +- Modify the `rpcuser` and `rpcpassword` values from the defaults below +- Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`) ```toml server=1 -rpcuser=your-bitcoind-username -rpcpassword=your-bitcoind-password testnet=1 -txindex=0 -listen=1 -rpcserialversion=0 -maxorphantx=1 +disablewallet=0 +datadir=/bitcoin +rpcuser=btcuser +rpcpassword=btcpass +rpcallowip=0.0.0.0/0 +dbcache=512 banscore=1 +rpcthreads=256 +rpcworkqueue=256 +rpctimeout=100 +txindex=1 [test] bind=0.0.0.0:18333 @@ -37,155 +54,51 @@ rpcbind=0.0.0.0:18332 rpcport=18332 ``` -Finally, start bitcoind as follows: - -```bash -bitcoind -conf=path/to/bitcoin.conf -``` - -It may take a few hours for the node to synchronize with the Bitcoin testnet. - -## Running a miner - -First, a keychain needs to be generated. First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. - -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `make_keychain` command, and pass `-t` to indicate that we want a testnet keychain. - -```bash -npx @stacks/cli make_keychain -t 2>/dev/null | json_pp > keychain.txt -``` - -After this runs, you should see some JSON in the new `keychain.txt` file that looks like this: - -```json -{ - "mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur", - "keyInfo": { - "privateKey": "2033269b55026ff2eddaf06d2e56938f7fd8e9d697af8fe0f857bb5962894d5801", - "address": "STTX57EGWW058FZ6WG3WS2YRBQ8HDFGBKEFBNXTF", - "btcAddress": "mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND", - "index": 0 - } -} -``` - -**Don't lose this information** - we'll need to use the `privateKey` field later on. +### Start Bitcoin -The above BTC address will then need to be imported into the BTC testnet network. - -```bash -bitcoin-cli -rpcport=18332 -rpcuser=your-user -rpcpassword=your-password importaddress -``` - -Once imported, we need to get some testnet BTC to that address. Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. You'll be sent `0.01` testnet BTC to that address. We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. You'll be sent 0.01 testnet BTC to that address. You'll be sent `0.01` testnet BTC to that address. - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... - -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` - -Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file. Replace the `seed` field with your private key. Save and close this configuration file. - -To run your miner, run this in the command line: +Finally, start bitcoind as follows: ```bash -stacks-node start --config=./testnet/stacks-node/conf/testnet-miner-conf.toml +bitcoind -conf=$HOME/bitcoin.conf ``` -Your node should start. Your node should start. It will take some time to sync, and then your miner will be running. - -### Creating an optimized binary - -The steps above are great for trying to run a node temporarily. The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run: To do so, use the same configuration as above, but run: - -```bash -cd testnet/stacks-node -cargo build --release --bin stacks-node -``` +:::note +It will take a few hours for the node to synchronize with Bitcoin testnet. +::: -The above code will compile an optimized binary. To use it, run: To use it, run: +While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): ```bash -cd ../.. -cd ../.. -cd ../.. -./target/release/stacks-node start --config=./testnet/conf/testnet-follower-conf.toml +$ bitcoin-cli \ + -rpcconnect=localhost \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpass \ +getblockchaininfo | jq .blocks +2417570 ``` -To read more about the technical details of mining on the Stacks 2.0 network, have a look at [the minig guide](../understand-stacks/mining): - -### Enable debug logging - -In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: In the command line, run: - -```bash -STACKS_LOG_DEBUG=1 stacks-node testnet -``` +--- -## Running a miner in Windows +## Running a Stacks Blockchain miner -### Prerequisites +First, download a [stacks blockchain binary](https://github.com/stacks-network/stacks-blockchain/releases/latest), or [build from source](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) -Make sure are [running a testnet node](run-a-node) before starting this tutorial. +_There may be some extra requirements to building, [defined here](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages)_ -### Generate keychain and get testnet tokens in Windows +:::tip It is recommened to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain` ::: -To setup the miner, first, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. +### Generate a keychain -To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. To get a keychain, the simplest way is to use the `stacks-cli`. We'll use the `stx make-keychain` command, and pass `-t` to indicate that we want a testnet keychain. +First, a keychain needs to be generated. First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a crytpocurrency exchange, and then use that BTC to start mining. First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. -Generate a keychain: +To create a keychain, the simplest way is to use the [stacks-cli](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. ```bash -npm install --global @stacks/cli -stx make_keychain -t > cli_keychain.json -type cli_keychain.json +npx @stacks/cli make_keychain -t 2>/dev/null | jq -r ``` -After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this: +After this runs, you should see some JSON printed to the screen that looks like this: ```json { @@ -199,162 +112,110 @@ After this runs, you'll probably see some installation logs, and at the end you } ``` -:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: +:::warning **Do not lose this information** - we'll need to use the `privateKey` and `btcAddress` fields in later steps. ::: -Request BTC from faucet: +The above `btcAddress` (mkRYR7KkPB1wjxNjVz3HByqAvVz8c4B6ND) will then need to be imported into the bitcoin testnet network. :::note Be sure to replace `` with the bitcoin address in the "Generate a keychain" step ::: -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. You'll be sent 0.01 testnet BTC to that address. You'll be sent 0.01 testnet BTC to that address. +```bash +bitcoin-cli \ + -rpcport=18332 \ + -rpcuser=btcuser \ + -rpcpassword=btcpassword \ +importaddress +``` -### Update configuration file +Once imported, we need to get some testnet BTC to that address. Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. You'll be sent `0.01` testnet BTC to that address. We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. You'll be sent 0.01 testnet BTC to that address. You'll be sent `0.01` testnet BTC to that address. -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). +### Update the Stacks Blockchain Configuration File -Update the following properties: +Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner config](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/testnet-miner-conf.toml`. -```toml -[node] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Now, grab your `privateKey` from earlier when you ran the `make_keychain` command. Replace the `seed` and `local_peer_seed` field with your private key. Save and close this configuration file. -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Next, update the bitcoin configuration: -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... +- **optional but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` +- From the `make_keychain` step, modify the `seed` and `local_peer_seed` values with `privatekey` +- Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) -[burnchain] -... +```toml [node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +seed = "" +local_peer_seed = "" +miner = true +bootstrap_node = "047435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1d51651f7f1d566532c804da506c117bbf79ad62eea81213ba58f8808b4d9504ad@testnet.stacks.co:20444" +wait_time_for_microblocks = 10000 [burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' +chain = "bitcoin" +mode = "xenon" peer_host = "127.0.0.1" -username = "" -password = "" -... +username = "" +password = "" +rpc_port = 18332 +peer_port = 18333 + +[[ustx_balance]] +address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" +amount = 10000000000000000 + +[[ustx_balance]] +address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" +amount = 10000000000000000 ``` -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. Replace the seed field with your private key. Save and close this configuration file. - -### Run the miner +### Start the Stacks Blockchain -To start your miner, run this in the command line: +To run your miner, run this in the command line: ```bash -stacks-node start --config=testnet/stacks-node/conf/testnet-miner-conf.toml +stacks-node start --config=$HOME/testnet-miner-conf.toml ``` - - -:::note -While starting the node for the first time, windows defender might pop up with a message to allow access. If so, allow access to run the node. -::: If so, allow access to run the node. -::: ![Windows Defender](/img/windows-defender.png) - - - Your node should start. Your node should start. It will take some time to sync, and then your miner will be running. -### Enable debug logging in Windows +### Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: In the command line, run: ```bash -set RUST_BACKTRACE=full; -set STACKS_LOG_DEBUG=1; -stacks-node start --config=testnet-miner-conf.toml +STACKS_LOG_DEBUG=1 stacks-node start --config=$HOME/testnet-miner-conf.toml ``` -## Optional: Running with Docker +--- + +## Optional: Running a Stacks Blockchain miner with Docker -Alternatively, you can run the testnet node with Docker. +Alternatively, you can run a Stacks testnet miner with Docker. -:::warning Ensure you have [Docker](https://docs.docker.com/get-docker/) installed on your machine. ::: ::: ::: +:::caution Ensure you have [Docker](https://docs.docker.com/get-docker/) installed ::: -### Generate keychain and get testnet tokens +### Generate a Keychain and Get Some Tokens Generate a keychain: ```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null +docker run -i node:14-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r ``` -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. You'll be sent 0.01 testnet BTC to that address. You'll be sent 0.01 testnet BTC to that address. - -### Update config file - -Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. Now, we need to configure our node to use this Bitcoin keychain. Clone the [stacks-blockchain repository](https://github.com/stacks-network/stacks-blockchain) to your local machine if you haven't already. In the `stacks-blockchain` folder, modify the file at [`testnet/stacks-node/conf/testnet-miner-conf.toml`](https://github.com/stacks-network/stacks-blockchain/blob/master/testnet/stacks-node/conf/testnet-miner-conf.toml). - -Update the following properties: - -```toml -[node] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... - -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... - -[burnchain] -... -[node] -... -seed = "replace-with-your-private-key" -local_peer_seed = "replace-with-your-private-key" -... +Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into this Bitcoin testnet faucet. You'll be sent `0.01` tBTC to that address. -[burnchain] -... -# To mine on Testnet, you need to run bitcoind locally -# Details can be found in above section, 'Running bitcoind locally' -peer_host = "127.0.0.1" -username = "" -password = "" -... -``` +### Update Stacks Blockchain Docker Configuration File -Now, grab your `privateKey` from earlier, when you ran the `stx make_keychain` command. Replace the seed field with your private key. Save and close this configuration file. Replace the seed field with your private key. Save and close this configuration file. +Use the steps oulined above to create the [configuration file](miner-testnet#update-the-stacks-blockchain-configuration-file) -### Start the miner +### Start the Stacks Blockchain miner with Docker :::info The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled ::: If removed, debug logs will be disabled ::: @@ -365,7 +226,8 @@ docker run -d \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ - -v "$(pwd))/testnet/stacks-node/conf/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ + -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-blockchain:latest \ @@ -378,26 +240,22 @@ You can review the node logs with this command: docker logs -f stacks_miner ``` +--- + ## Optional: Running in Kubernetes with Helm -In addition, you're also able to run a testnet node in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). +In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chart](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain). -Ensure you have the following prerequisites installed on your machine: +Ensure you have the following prerequisites installed: - [Docker](https://docs.docker.com/get-docker/) - [minikube](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) - [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - [helm](https://helm.sh/docs/intro/install/) -### Generate keychain and get some testnet tokens - -Generate a keychain: - -```bash -docker run -i node:14-alpine npx @stacks/cli make_keychain -t 2>/dev/null -``` +### Generate keychain and get some tokens -We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. We need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent 0.01 testnet BTC to that address. Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucet](https://tbtc.bitaps.com/). You'll be sent `0.01` testnet BTC to that address. You'll be sent 0.01 testnet BTC to that address. You'll be sent 0.01 testnet BTC to that address. +Use the steps [outlined above](miner-testnet#generate-a-keychain-and-get-some-tokens) ### Install the chart and run the miner @@ -408,7 +266,7 @@ minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ - --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" + --set config.node.seed="replace-with-your-privateKey-from-generate-keychain-step" \ ``` You can review the node logs with this command: diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md new file mode 100644 index 0000000000..1281964689 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/quicknode.md @@ -0,0 +1,45 @@ +--- +title: Run a Node with QuickNode +description: A guide to setup Stacks on QuickNode +sidebar_position: 4 +tags: + - tutorial +--- + +[QuickNode](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. + +As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. + +To get started, [set up an account](https://www.quicknode.com/signup) on QuickNode. + +Once you are signed in, getting set up with your own Stacks node is a matter of a few clicks, starting with 'Create an endpoint'. + +![Set up a QuickNode endpoint](./quicknode-endpoint.png) + +From there, you just need to select Stacks, your desired network, and your desired QuickNode plan level. + +_That's it._ + +You now have an API endpoint URL you can use to connect to Stacks. + +How do you do that? + +It depends on the frontend framework you are using, but let's see how to do it with Stacks.js. + +First, you'll need to install the `@stacks/network` package. + +Next we'll import it: + +```javascript +import { StacksTestnet } from "@stacks/network"; +``` + +Then in your frontend, set up the network with the following line: + +```javascript +const network = new StacksTestnet({ url: "" }); +``` + +Then you can call transactions like you normally would using the `@stacks/transactions` library. + +For an example of how to do this, please refer to the [Hello Stacks](../tutorials/hello-stacks.md) tutorial. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md index 94d938c5ca..2993568ce4 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/run-a-node.md @@ -1,5 +1,5 @@ --- -title: Run a node +title: Run a Node with Docker description: Set up and run a Stacks node sidebar_position: 1 tags: @@ -8,344 +8,99 @@ tags: ## Stacks Blockchain with Docker -Run your own Stacks Blockchain node easily with just few commands. +Run your own Stacks Blockchain node using [docker-compose](https://docs.docker.com/compose/) with just few commands using [stacks-blockchain-docker](https://github.com/stacks-network/stacks-blockchain-docker) -This tutorial describes a simple and effective [quickstart](#quickstart) to run a Stacks node using public scripts hosted in [Stacks Blockchain repository](https://github.com/stacks-network/stacks-blockchain-docker). Valid for mainnet, testnet and mocknet. +- [Quickstart](./run-a-node#quickstart) +- [Requirements](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/requirements.md) +- [Docker Setup](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/docker.md) +- [Configuration](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/config.md) +- [Upgrading](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) +- [Common Issues](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/issues.md) -## **Quickstart** - -1. **Clone the stacks-blockchain-docker repository locally** - -```bash -git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker -``` - -2. **Optionally, create/copy `.env` file**. If file `.env` doesn't exist when launched it will be created from `sample.env` automatically. - -```bash -cp sample.env .env -``` - -_You may also use a symlink as an alternative to copying: `ln -s sample.env .env`_ - -3. **Optionally, ensure all images are up to date** - -```bash -./manage.sh -n -a pull -``` - -4. **Start the Services** - -```bash -./manage.sh -n -a start -``` +## **Requirements:** -- With optional proxy: +The **minimum viable requirements** are listed below. -```bash -./manage.sh -n -a start -f proxy -``` +While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. -- With optional bitcoin node: +- ⚠️ [docker-compose](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** +- **4GB memory** +- **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) +- **100GB disk** ( _minimum of 150GB SSD is recommended_ ) -```bash -./manage.sh -n -a start -f bitcoin -``` +:::caution MacOS with an ARM processor is NOT recommended -5. **Stop the Services** +The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi work as expected. ::: -```bash -./manage.sh -n -a stop -``` - -6. **Retrieve Service Logs** - -```bash -./manage.sh -n -a logs -``` - -- Export docker log files to `./exported-logs`: +## **Quickstart** -This will create one log file for every running service, for example: postgres.log, stacks-blockain.log, stacks-blockchain-api.log and bitcoin-core.log. -Notice that each time you run this command the log files will be overwritten. +The `` placeholder used below can be replaced with one of: -```bash -./manage.sh -n -a logs export -``` +- mainnet +- testnet +- mocknet -7. **Restart all services** +1. **Clone the stacks-blockchain-docker repository locally** ```bash -./manage.sh -n -a restart +git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker ``` -- With optional proxy: +2. **Start the Services** ```bash -./manage.sh -n -a restart -f proxy +./manage.sh -n -a start ``` -8. **Delete** all data in `./persistent-data/` and/or data of the Bitcoin blockchain. - - This data is owned by root, so you will need to run it with sudo privileges so it can delete the data. +:::note With an optional HTTP proxy on port 80: ```bash -$ sudo ./manage.sh -n -a reset - -Please confirm what persistent data you wish to delete: - -0. Cancel -1. Delete Persistent data for Stacks testnet only and leave Bitcoin blockchain data unaffected. -2. Delete Persistent data for Stacks testnet and Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin -3. Delete Persistent data for Bitcoin blockchain data in ./persistent-data/blockchain-bitcoin only. -Please note that BNS data will never get deleted. - -Type 0, 1, 2 or 3: 2 - -Ok. Delete Stacks and Bitcoin data. -[ Success ] Persistent data deleted for Bitcoin blockchain. -[ Success ] Persistent data deleted for Stacks testnet. - +./manage.sh -n -a start -f proxy ``` -9. **Download BNS data to** `./persistent-data/bns-data` - -```bash -./manage.sh bns -``` +::: -10. **Export stacks-blockchain-api events** (_Not applicable for mocknet_) +## **Accessing the services** -```bash -./manage.sh -n -a export -# check logs for completion -./manage.sh -n -a restart -``` +:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. -11. **Replay stacks-blockchain-api events** (_Not applicable for mocknet_) +Follow the logs to track the sync progress: ```bash -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart +./manage.sh -n -a logs ``` -## **Running also a bitcoin node (Optional)** - -Stacks needs to use a Bitcoin node, and by default when you run a Stacks node you will be using a public Bitcoin node, which is configured in the `.env` file. Default values is `BITCOIN_NODE=bitcoin.mainnet.stacks.org`. - -However, you can optionaly run both nodes together and configured in a way that you Stacks node will use your own Bitcoin node instead of a public one. - -If you run the script with a bitcoin node it will download and build it directly from source for increased security. This process which only needs to happen once can take up to 20-30 minutes depending on the speed of your system. Also, once the bitcoin node is up and running it will need an additional time for sync for the first time (can be hours for testnet and days for mainnet). - -### Why run Stacks node with your own Bitcoin node? - -Because running your own Bitcoin node will give you higher security and improved perfomance. - -* **Improved perfomance**: The Bitcoin node will serve you blocks faster, as well as UTXOs for your miner (if you run one). -* **Higher security**: The Bitcoin node will also have validated all bitcoin transactions the Stacks node consumes. If you don't run your own Bitcoin node, you're relying on the SPV headers to vouch for the validity of Bitcoin blocks. - -The disadvantage of running your own Bitcoin node is that you need the extra space to store the Bitcoin blockchain (about 500GB) and the initial time it will take to download this data the first time. - -### Example - -You can run easily run your Stacks node with your own Bitcoin node by adding the flag `bitcoin`. This is available only for testnet and mainnet. - -Example: `./manage.sh -n mainnet -a start -f bitcoin` or `./manage.sh -n testnet -a start -f bitcoin` - -### Bitcoin node configuration - -In the `.env` file there is the variable `BITCOIN_BLOCKCHAIN_FOLDER`. As the bitcoin blockchain can be large (over 500GB) you optionally change this variable to any location of your choosing. If you have previously used the [bitcoin core application](https://bitcoin.org/en/bitcoin-core/) and already have the bitcoin blockchain synced, you can use the same data folder and avoid redownloading the entire bitcoin blockchain. - -## **Accessing the services** - -:::tip For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - -Use the command `./manage.sh -n -a logs` to check the sync progress. ::: +::: **stacks-blockchain**: -- Ports `20443-20444` are exposed to `localhost` +- Ports `20443-20444` are exposed on `localhost` ```bash -curl -sL localhost:20443/v2/info | jq +curl -sL localhost:20443/v2/info | jq -r ``` **stacks-blockchain-api**: -- Port `3999` are exposed to `localhost` +- Port `3999` is exposed on `localhost` ```bash -curl -sL localhost:3999/v2/info | jq +curl -sL localhost:3999 | jq -r ``` **proxy**: -- Port `80` is exposed to `localhost` +- Port `80` is exposed on `localhost` ```bash -curl -sL localhost/v2/info | jq -curl -sL localhost/ | jq +curl -sL localhost/v2/info | jq -r +curl -sL localhost | jq -r ``` --- ## Upgrades -⚠️ For upgrades to running instances of this repo, you'll need to [run the event-replay](https://github.com/hirosystems/stacks-blockchain-api#event-replay): - -```bash -./manage.sh -n -a stop -./manage.sh -n -a export -./manage.sh -n -a import -./manage.sh -n -a restart -``` +:::caution For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replay](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md): ::: --- - -## **Workarounds to potential issues** - -_**Port(s) already in use**_: - -- If you have a port conflict, typically this means you already have a process using that same port.\ - To resolve, find the port you have in use (i.e. `3999` and edit your `.env` file to use the new port. - -```bash -netstat -anl | grep 3999 -``` - -``` -tcp46 0 0 *.3999 *.* LISTEN -``` - -_**Containers not starting (hanging on start)**_: - -- Occasionally, docker can get **stuck** and not allow new containers to start. If this happens, simply restart your docker daemon and try again. - -_**Database Issues**_: - -- For any of the various Postgres/sync issues, it may be easier to simply remove the persistent data dir. Note that doing so will result in a longer startup time as the data is repopulated. - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a start -``` - -_**API Missing Parent Block Error**_: - -- If the Stacks blockchain is no longer syncing blocks, and the API reports an error similar to this:\ - `Error processing core node block message DB does not contain a parent block at height 1970 with index_hash 0x3367f1abe0ee35b10e77fbcaa00d3ca452355478068a0662ec492bb30ee0f13e"`,\ - The API (and by extension the DB) is out of sync with the blockchain. \ - The only known method to recover is to resync from genesis (**event-replay _may_ work, but in all likelihood will restore data to the same broken state**). - -- To attempt the event-replay - -```bash -./manage.sh -n -a stop -./manage.sh -n -a import -# check logs for completion -./manage.sh -n -a restart -``` - -- To wipe data and re-sync from genesis - -```bash -./manage.sh -n -a stop -./manage.sh -n -a reset -./manage.sh -n -a restart -``` - - -## **Requirements:** - -- [Docker](https://docs.docker.com/get-docker/) >= `17.09` -- [docker-compose](https://github.com/docker/compose/releases/) >= `1.27.4` -- [git](https://git-scm.com/downloads) -- [jq binary](https://stedolan.github.io/jq/download/) -- [sed](https://www.gnu.org/software/sed/) -- Machine with (at a minimum): - - 4GB memory - - 1 Vcpu - - 50GB storage (600GB if you optionally also run the bitcoin mainnet node) - -:::caution MacOS with an M1 processor is NOT recommended - -The way Docker for Mac on an Arm chip is designed makes the I/O incredibly slow, and blockchains are **_very_** heavy on I/O. This only seems to affect MacOS, other Arm based systems like Raspberry Pi's seem to work fine. - -::: - - -### Install/Update docker-compose - -:::note `docker-compose` executable is required, even though recent versions of Docker contain `compose` natively ::: - -- [Install Docker-compose](https://docs.docker.com/compose/install/) -- [Docker Desktop for Mac](https://docs.docker.com/docker-for-mac/install/) -- [Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/install/) -- [Docker Engine for Linux](https://docs.docker.com/engine/install/#server) - -First, check if you have `docker-compose` installed locally. - -To do that, run this command in your terminal : - -```bash -docker-compose --version -``` - -Output should look something very similar to this : - -``` -docker-compose version 1.27.4, build 40524192 -``` - -If the command is not found, or the version is < `1.27.4`, run the following to install the latest to `/usr/local/bin/docker-compose`: - -```bash -#You will need to have jq installed, or this snippet won't run. -VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r) -DESTINATION=/usr/local/bin/docker-compose -sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION -sudo chmod 755 $DESTINATION -``` - -### Security note on docker - -The Docker daemon always runs as the root user so by default you will need root privileges to interact with it. - -The script `manage.sh` uses docker, so to avoid the requirement of needing to run the script with root privileges it is prefered to be able to *manage Docker as a non-root user*, following [these simple tests](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user). - -This will avoid the need of running the script with root privileges for all operations except the removal of data. - -### Configuration files you can edit - -The following files can be modified to personalize your node configuration, but generally most of them should be left as-is. All these files will be created from the sample copy if they don't exist at runtime (for example `.env` is created from `sample.env`). However these files will never be modified by the application once created and will never be pushed back to github, so your changes will be safe. - -* `.env` -* `./conf/mainnet/Config.toml` -* `./conf/mainnet/bitcoin.conf` -* `./conf/testnet/Config.toml` -* `./conf/testnet/bitcoin.conf` - -By default: - -- BNS data is **not** enabled/imported - - To enable, uncomment `# BNS_IMPORT_DIR=/bns-data` in `./env` - - Download BNS data: `./manage.sh bns` -- Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_FT_METADATA=1` in `./env` -- Non-Fungible token metadata is **not** enabled - - To enable, uncomment `# STACKS_API_ENABLE_NFT_METADATA=1` in `./env` -- Verbose logging is **not** enabled - - To enable, uncomment `# VERBOSE=true` in `./env` -- Bitcoin blockchain folder is configured in `BITCOIN_BLOCKCHAIN_FOLDER` in `./env` - -### Local Data Dirs - -Directories will be created on first start that will store persistent data under `./persistent-data/` - -`` can be 1 of: - -- mainnet -- testnet -- mocknet diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md index ea9a1e45d3..4c432bc86b 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/stacks-node-configuration.md @@ -1,7 +1,7 @@ --- title: Stacks Node Configuration description: Configuration parameters and options for the stacks-node binary -sidebar_position: 6 +sidebar_position: 4 --- ## Usage @@ -10,97 +10,141 @@ sidebar_position: 6 stacks-node sub-command [--subcommand-option ] ``` -## Subcommands +### Subcommands -:::caution The `stacks-node` binary may have deprecated commands that are not documented on this page. Deprecated commands may be accessible until they are fully removed from the sources. ::: +- `mocknet`: start a mocknet instance using defaults +- `testnet`: start a testnet instance using defaults (chainstate is not persistent) +- `mainnet`: start a mainnet instance using defaults (chainstate is not persistent) +- `start`: combined with `--config`, starts an instance with a specified configuration file +- `version`: displays binary version +- `help`: displays the help message -### mocknet +## Configuration File Options -Start a node based on a fast local setup emulating a burnchain. Ideal for smart contract development. Ideal for smart contract development. Ideal for smart contract development. +The Stacks Blockchain configuration file has multiple sections under which an option may be placed. -Example: +- [node](./stacks-node-configuration#node) +- [events_observer](./stacks-node-configuration#events_observer) +- [connection_options](./stacks-node-configuration#connection_options) +- [burnchain](./stacks-node-configuration#burnchain) +- [ustx_balance](./stacks-node-configuration#ustx_balance) -```bash -stacks-node mocknet -``` +For reference, several configuration file examples are [available here](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf) -### krypton +- [Example mainnet follower configuration](./stacks-node-configuration#example-mainnet-follower-configuration) -Start a node that will join and stream blocks from the public krypton regtest, powered by Blockstack via [Proof of Transfer](../understand-stacks#consensus-mechanism). sidebar_position: 1 sidebar_position: 1 +### node -Example: +Contains various configuration options for the stacks-node binary. -```bash -stacks-node krypton -``` +| Name | Required | Description | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | +| rpc_bind | ✓ | IPv4 address and port to open for RPC connections | +| p2p_bind | ✓ | IPv4 address and port to open for P2P connections | +| working_dir | | Absolute path to the directory where chainstate data will be stored | +| data_url | | IPv4 address and port for incoming RPC connections | +| p2p_address | | IPv4 address and port for incoming P2P connections | +| bootstrap_node | | Public key, IPv4 address, and port to bootstrap the chainstate | +| wait_time_for_microblocks | | The amount of time in ms to wait before trying to mine a block after catching up to the anchored chain tip | +| seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for mining. Only needed if `miner` is set to `true` | +| local_peer_seed | | The [private key](./miner-mainnet#generate-a-keychain) to use for signing P2P messages in the networking stack | +| miner | | Determines whether the node is running a follower (`false`) or a miner (`true`). Defaults to `false` | +| mock_miner | | Simulates running a miner (typically used for debugging) | +| mine_microblocks | | Determines whether the node will mine microblocks. Will only take effect if `miner` is set to `true` | +| prometheus_bind | | Address and port for Prometheus metrics collection. | -### testnet +### events_observer -Start a node that will join and stream blocks from the public testnet. +:::info This section is _optional_ and not required -Example: +However, if this section is added, **all** fields are required ::: Contains options for sending events emitted to the [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service. -```bash -stacks-node testnet -``` +| Name | Required | Description | +| ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | ✓ | Address and port to a [stacks-blockchain-api](https://github.com/hirosystems/stacks-blockchain-api) service | +| retry_count | ✓ | Number of times to retry sending events to the endpoint before failing | +| events_keys | ✓ | Event keys for which to watch. Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. Event keys for which to watch. Event keys for which to watch. The emitted node events can be restricted by account, function name and event type. Asterix ("\*") can be used to emit all events. Asterix ("\*") can be used to emit all events. | | -### mainnet +### connection_options -Start a node that joins and streams blocks from the public mainnet. +:::info This section is _optional_ and not required. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node mainnet -``` - -### start - -Start a node with a config of your own. Start a node with a config of your own. Start a node with a config of your own. Can be used for joining a network, starting a new chain, or replacing default values used by the `mocknet` or `testnet` subcommands. +Specifies configuration options for others connecting to the stacks node. -#### Arguments +| Name | Required | Description | +| ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| public_ip_address | ✓ | Public IPv4 to advertise to other nodes | +| download_interval | ✓ | Time (in seconds) between attempts to download blocks | +| walk_interval | ✓ | Time (in seconds) between attempts to walk the list of neighbors | +| read_only_call_limit_read_length | ✓ | Total number of bytes allowed to be read by an individual read-only function call | +| read_only_call_limit_read_count | ✓ | Total number of independent read operations permitted for an individual read-only function call | +| read_only_call_limit_runtime | ✓ | [Runtime cost](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) limit for an individual read-only function call | -**--config**: relative or absolute path to the TOML config file. Required. Required. Required. +### burnchain -Example: +This section contains configuration options pertaining to the blockchain the stacks-node binds to on the backend for proof-of-transfer (BTC). -```bash -stacks-node start --config=/path/to/config.toml -``` +| Name | Required | Description | +| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| chain | ✓ | The blockchain stacks-node binds to on the backend for proof-of-transfer. Only value supported: `"bitcoin"`. Only value supported: `"bitcoin"`. Only value supported: `bitcoin` | +| mode | ✓ | The profile or test phase of which to run stacks-node. The profile or test phase of which to run stacks-node. Valid values are `"mocknet"`, `"helium"`, `"neon"`, `"argon"`, `"krypton"`, `"xenon"`. Valid values are [ `mocknet`, `testnet`, `xenon`, `mainnet` ] | +| peer_host | | FQDN of the host running the backend Bitcoin blockchain | +| rpc_port | | RPC port of `peer_host` | +| peer_port | | P2P port of `peer_host` | -See [Configuration File Options](#configuration-file-options) for more information. +#### Mining -#### version +| Name | Required | Description | +| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------- | +| burn_fee_cap | ✓ | Maximum amount (in sats) of "burn commitment" to broadcast for the next block's leader election | +| satoshis_per_byte | ✓ | [Amount (in sats) per byte](https://bitcoinfees.net/) - Used to calculate the transaction fees | +| commit_anchor_block_within | | Sets the time period (in milliseconds) for commitments. Only used when `mode` is set to `mocknet`. | -Displays information about the current version and the release cycle. +### ustx_balance -Example: +- `mocknet`/`testnet` only -```bash -stacks-node version -``` +This section contains configuration options allocating microSTX per address in the genesis block -#### help +This section can repeat multiple times, but each section can only define a single address. -Displays a help message. +:::info This section is only required for the `testnet` and `mocknet` networks. -Example: +However, if this section is added, **all** fields are required ::: -```bash -stacks-node help -``` +| Name | Required | Description | +| ------- | -------- | --------------------------------------------------------------------- | +| address | ✓ | Address which maintains a microSTX balance | +| amount | ✓ | The balance of microSTX given to the address at the start of the node | -## Configuration File Options +## Example Mainnet Follower Configuration -The TOML configuration file has multiple sections under which an option may be placed. +```toml +[node] +working_dir = "/stacks-blockchain" +rpc_bind = "0.0.0.0:20443" +p2p_bind = "0.0.0.0:20444" +bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" -To see a list of example configurations, [please see this page](https://github.com/stacks-network/stacks-blockchain/tree/master/testnet/stacks-node/conf). +[burnchain] +chain = "bitcoin" +mode = "mainnet" +peer_host = "localhost" +username = "user" +password = "pass" +rpc_port = 8332 +peer_port = 8333 -### Section: node +[[events_observer]] +endpoint = "localhost:3700" +retry_count = 255 +events_keys = ["*"] +``` -Contains various configuration options pertaining to the stacks-node. -Example: + diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md index 094e3f03a1..18e8dd3a48 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/nodes-and-miners/verify-miner.md @@ -7,7 +7,7 @@ sidebar_position: 7 You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: ```bash -$ head -n 100 /path/to/your/node/logs | grep -i utxo +$ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node -``` \ No newline at end of file +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/references/glossary.md b/i18n/zh/docusaurus-plugin-content-docs/current/references/glossary.md index b315c60d84..9857303579 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/references/glossary.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/references/glossary.md @@ -5,19 +5,16 @@ description: A comprehensive list of terms used within the ecosystem. A comprehensive list of terms used within the ecosystem. -#### App Review -An incentive mechanism for application developers in the early stage (first four years) of the ecosystem and helps with bootstrapping the two-sided market. - #### Atlas A peer network provide a global index for discovery. #### Bitcoin (BTC) address -A string of letters and numbers. A string of letters and numbers. A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. +A string of letters and numbers. `3E53XjqK4Cxt71BGeP2VhpcotM8LZ853C8` Sharing this address allows anyone to send Bitcoin to the address. -#### block +#### Block A discrete group of records written to a blockchain that can effectively be identified and referenced by the use of headers that contain a digital fingerprint of the records each block contains. -#### blockchain +#### Blockchain A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. A database created and shared by the members of a peer-to-peer computer network which each member of that network can independently trust due to the rules governing the database’s creation. A blockchain can therefore be used to replace centralized databases. A blockchain can therefore be used to replace centralized databases. #### Blockchain Name System (BNS) @@ -33,138 +30,127 @@ Looks like a bitcoin address but starts with `ID` for example: `ID-1J3PUxY5uDShU #### Burning Burning a token means that the token is transferred to an address that is a black hole—one that is not owned by any entity and for which guessing the applicable private key is effectively impossible based on known mathematical principles. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. This effectively destroys the token by making it unavailable for future use and decreases the total number of tokens available from that point forward. -#### consensus hash +#### Consensus hash A consensus hash is a cryptographic hash that each node calculates at each block. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. It is derived from the accepted state transitions in the last-processed block and a geometric series of prior-calculated consensus hashes. #### Consensus rules -"The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. +The rules governing the creation of new valid records in a blockchain database and the mining algorithms used for this purpose. -#### control plane +#### Control plane The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. The part of a network that carries signaling traffic and is responsible for routing. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. Control packets originate from or are destined for a router. Functions of the control plane include system configuration and management. Functions of the control plane include system configuration and management. -#### core node +#### Core node A server that runs Stacks Blockchain services. -#### crypto-asset +#### Crypto asset A digital asset which utilises cryptography, peer-to-peer networking and a public ledger to regulate the creation of new units, verify transactions and secure the transactions without the intervention of any middleman. -#### cryptography +#### Cryptography The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. The practise and study of encryption and decryption - encoding data so that it can only be decoded by specific individuals. A system for encrypting and decrypting data is a cryptosystem. A system for encrypting and decrypting data is a cryptosystem. #### DAO See Decentralized Autonomous Organization. -#### decentralized application (DApp) +#### Decentralized application (DApp) A DApp is a service that enables direct interaction between end users and providers (e.g. connecting buyers and sellers in some marketplace, owners and stores in file storage). A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" A term coined by Ethereum. See their glossary: http://ethdocs.org/en/latest/glossary.html#dapp" #### Decentralized Autonomous Organization A type of contract or suite of contracts on the blockchain that is intented to codify, enforce or automate the processes of an organization. -#### digital asset -Also referred to as a crypto-asset. Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. +#### Digital asset +Also referred to as a crypto asset. Also referred to as a crypto-asset. Any set of unique digital information—including, for example, programs, decentralized programs, isolated chunks of programming code, collections of data, e-mail or web addresses or cryptocurrency tokens—that is capable of being stored and uniquely tracked on a computer network such as the Stacks network and over which a user can maintain control through that network. -#### digital fingerprint +#### Digital fingerprint A digital fingerprint is a unique number of a fixed length that can be produced by running any set of digital information through something called a cryptographic hash function. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. Each set of digital information (including a digital asset, and the digital record of any network operation on that digital asset) should (as a practical matter) have a unique digital fingerprint, which allows that set of digital information to be identified. However, it is almost impossible to recreate a digital asset from its digital fingerprint. The Blockstack network uses industry-standard algorithms such as SHA-256 to create digital fingerprints. -#### digital signature +#### Digital signature A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. A digital signature is a sequence of digital information combining a user’s private key and any digital information that the user wishes to sign. Any other party can use the user’s paired public key to verify that the digital signature is authentic, i.e. that the public key was generated from a particular piece of digital information and the user’s private key. -#### distributed hash tables (DHT) +#### Distributed hash tables (DHT) A form of network used to store some content in the form of key/value pairs. ... A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. ... A form of network used to store some content in the form of key/value pairs. ... This experimental project try to avoid keeping all the blockchain, but instead prefers to store it in a DHT. -#### ephemeral key +#### Ephemeral key A cryptographic key is called ephemeral if it is generated for each execution of a key establishment process. -#### fork +#### Fork The term fork is used to refer both to any situation where there are two or more competing versions of a blockchain on a network (a situation that may arise and resolve itself in the ordinary course of network operations due to lags in communication between core nodes) and any software update that is proposed for adoption by the core nodes of a blockchain network that may result in a persistent fork on the network, with core nodes that adopt the update recognizing one version of the blockchain and those which do not recognizing another. #### Gaia Decentralized storage architecture for off-chain data. More info [here](../gaia). More info [here](../gaia). More info [here](../gaia). -#### genesis block +#### Genesis block The genesis block is the first block of the Stacks blockchain, which will create the initial 1.32 billion Stacks Tokens. -#### id.blockstack -An identifier in the Blockstack, for example meepers.id.blockstack. This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" This is your name & identity that is registered in the .id namespace on Blockstack. Your personal data and storage are built around this ID. Apps that want to access your data use your permission and identity to find it. An id is usually a shorthand for a longer, hash ID string, for example ID-1Fj9kkw15P51Fj9kkw15P5xJmyefWhLKrQMKNPREfaqsJ" - -#### identity - -A way to identify a person or an organization on the Stacks network. A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. A way to identify a person or an organization on the Stacks network. An identity is unique, both `meepers.id.blockstack` or `chad.id` are examples of IDs. +#### (Digital) Identity +A way to represent a collection of activities in the digital world that are controlled by one or more persons, representatives of an organization or in general an entity, for example a software program. On the Stacks network, an identity is represented by a Stacks address and can have an associated unique name (see BNS) and a public profile. -#### identity management (IDM) -Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason". +#### Identity management (IDM) +Identity management, also known as identity and access management is, in computer security, the security and business discipline that enables the right individuals to access the right resources at the right times and for the right reason. -#### know your customer (KYC) -Or KYC, is a popular term used in the banking or financial field. Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. +#### Know your customer (KYC) +KYC is a popular term used in the banking or financial field. Or KYC, is a popular term used in the banking or financial field. KYC is a process where financial institutions, insurers and other companies obtain information about the identity and address of the customers as part of risk management. -#### light clients +#### Light clients Clients that can independently validate the existence of transactions by downloading only block headers and not the entire blockchain. -#### magic recovery code - -A long encrypted string, for example: `36mWivFdy0YPH2z31EflpQz/Y0UMrOrJ++lH=0EI7c3mop2JuRBm5WXxSTazJsUjOA...` Do not share the QR code that accompanied your recovery code either. This is a QR code: - -![](/img/qr-code.png) - -#### mesh network +#### Mesh network A local network topology in which the infrastructure nodes (i.e. bridges, switches, and other infrastructure devices) connect directly, dynamically and non-hierarchically to as many other nodes as possible and cooperate with one another to efficiently route data from/to clients. -#### mining +#### Mining Mining generally refers to the process of performing certain functions for a network such as adding new records to a blockchain in exchange for mining rewards; it may also refer to other mechanisms whereby rewards (usually in the form of cryptocurrency) are provided for performing other tasks helpful to the network. -#### mining power +#### Mining power A miner’s (or group of miners’) mining power is equal to the probability it will be selected to write a new block to the blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. Depending on the mechanism for mining, this is usually related to the overall share of computing power or cryptoassets the miner or miners possess relative to all miners for that blockchain. -#### mining rewards +#### Mining rewards Mining rewards are newly issued tokens received by miners in exchange for adding new records to the blockchain or other activities beneficial to the network. -#### name +#### Name An identifier or name. Names are a type of digital asset in the Stacks network. An identifier or name. Names are a type of digital asset in the Stacks network. If you have signed into the Stacks Wallet, you might have created a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. If an application developer registered an application within Stacks, then they registered a name. Public Stacking pools can also have a name. -#### network operation +#### Network operation A network operation is any change to the information about a digital asset (or smart contract) stored on a blockchain, including, for example, a change in the digital asset’s owner, or a change in the location at which it is stored on the network. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. How and when these network operations are performed for each digital asset is governed, on the Blockstack network, either by the Stacks Node software or a smart contract. #### NFT Non fungible token. -#### private key +#### Private key -Private keys matches a corresponding public key. Private keys matches a corresponding public key. Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: +Private keys matches a corresponding public key. Private keys matches a corresponding public key. Private keys matches a corresponding public key. A public key also looks like a string of letters and numbers: ![](/img/private.png) The exact format of the public and private key depend on the software you use to create them. -#### proof-of-burn mining +#### Proof of burn mining The consensus algorithm used in the Stacks blockchain where miners destroy a proof-of-work-based cryptocurrency (currently Bitcoin) to get tokens; this enables the functionality where nodes can select between conflicting blockchain forks, as the blockchain fork with the most amount of cryptocurrency burned is considered to be the correct fork. -#### proof-of-work +#### Proof of work (PoW) A proof-of-work system or proof-of-work mining is a mining mechanism where miners must expend computing power to solve complicated cryptographic puzzles, and prove that they have done so by writing the solution to the blockchain, in order to be allowed to add blocks to a blockchain. This is the mining system used, for example, by Bitcoin. This is the mining system used, for example, by Bitcoin. This is the mining system used, for example, by Bitcoin. -#### public key +#### Public key Public and private key pair comprise of two uniquely related cryptographic keys. Public and private key pair comprise of two uniquely related cryptographic keys. Public and private key pair comprise of two uniquely related cryptographic keys. It looks like a long random string of letters and numbers: `3048 0241 00C9 18FA CF8D EB2D EFD5 FD37 89B9 E069 EA97 FC20 …` The exact format of the public and private key depend on the software you use to create them. #### Public Key Infrastructure (PKI) A system which returns a cryptographic public key associated with a name. -#### replicated state machines (RSMs) +#### Replicated state machines (RSMs) This is a model for reasoning about distributed computer programs -- any program (plus it's input) can be represented as a state machine, and when trying to get a distributed set of servers to agree on the output of an algorithm, you can model that process as N different state machines" -#### Secret recovery Key, -Used to access an identity on the Stacks blockchain. Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` Used to access an identity on the Stacks blockchain. A 24-word sequence of words for example: `applied binge crisp pictorial fiery` `dancing agreeable frogs light finish ping apple` +#### Secret Key +A different word for "Seed phrase". -#### seed phrase +#### Seed phrase +Used to access one or more identities on the Stacks blockchain and Bitcoin blockchain. The seed phrase consists of 24 words in a sequence. Both the word *and its position in the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -Used to access Stacks Wallet software. The seed phrase consists of 24 words in a sequence. Both the word *and its position the sequence* are important. Write down your seed phrase and store it in a secure location such as a safe deposit box. When you write the seed phrase down, include its position, for example,`1-frog, 2-horse, 3-building` and so on until you reach a final position `24-ocean`. -#### smart contract +#### Smart contract A smart contract is a computer program written to a blockchain such as the Stacks blockchain by developers. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. This computer program defines the various network operations that can be performed on the digital assets on the blockchain, the computations that can be performed using the smart contract, along with defining various important properties of the respective digital assets like ownership rights and the cost in fuel required to register the digital assets. -#### soft fork +#### Soft fork A soft fork is a proposed update to the software governing the network that results in a post-update network that is compatible with the network as it existed prior to the update, because it restricts the network operations that can be performed after the update. #### Stacks (STX) address - - A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with the Stacks Wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " You access a software wallet with a *seed phrase*. " You access a software wallet with a *seed phrase*. " + A STX address is a string of letters and numbers starting with an `SP` or `SM`, for example: `SM3KJBA4RZ7Z20KD2HBXNSXVPCR1D3CRAV6Q05MKT` If you created a software-only wallet with a Stacks wallet software, the wallet has a single STX address which is also sometimes called the *wallet address*. You access a software wallet with a *seed phrase*. " #### Stacks blockchain The Stacks blockchain is the custom blockchain being developed for use by the Stacks network that will use the Stacks token as its native currency and which will include the genesis block and subsequent blocks created by the mining activities described in the Stacks Network—Development of the Stacks network. @@ -178,32 +164,26 @@ A complete version of our open-source software available on Github at https://gi #### Stacks wallet An application for accessing assets, identity and storage. More information and example [here](../services-using-stacks/wallets). An application for accessing assets, identity and storage. Examples are the [Hiro Wallet](https://www.hiro.so/wallet), [xverse](https://www.xverse.app/) and [dcent](https://dcentwallet.com/). -#### storage hub -A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location. +#### Storage hub +A Gaia instance run by a hub provider or software. A Gaia hub stores data in a separate, addressed location associated with a public key. -#### storage provider +#### Storage provider A third-party company cloud or software provider that hosts one or more Gaia storage hubs. -#### transaction +#### Transaction A transaction is a unit of work within a block. -#### transaction fee -Fees paid by participants in a transaction to miners. +#### Transaction fee +Fees paid by participants of a blockchain to miners for their work to process transactions. -#### two-sided market problem +#### Two-sided market problem Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. Economic platforms having two distinct user groups that provide each other with network benefits. The Stacks platform is a classic two-sided market. The Stacks platform is a classic two-sided market. -#### username -A shorthand name for your id.blockstack. - -#### virtual blockchain -A layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. - -#### wallet address -A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. +#### Wallet address +A wallet address is the form in which a public key can be presented and recorded on a blockchain. Wallet addresses are therefore used to assign the ownership of digital assets on the Blockstack network. Wallet addresses are therefore used to assign the ownership of digital assets on the Stack network. -#### watch-only wallet -A wallet without send and receive ability. A wallet without send and receive ability. You can view only balances and transaction history. +#### Watch-only wallet +A wallet without send ability. A wallet without send and receive ability. You can view only balances and transaction history. #### web of trust mining Web-of-trust mining provides incentive mechanisms for users where an initial trusted-set of unique users is curated in the genesis block and, in the future, the initial set of users can expand the web-of-trust after the network goes live. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md index c3fc0556bf..58717a3234 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/defi.md @@ -8,7 +8,7 @@ They are multiple De-Fi sites that operate on the Stacks blockchain. :::tip Are we missing one? Please edit this page to add any relevant new site that we are missing. -::: Please edit this page to add any relevant new site that we are missing. ::: +::: ## Alex @@ -26,7 +26,7 @@ Please edit this page to add any relevant new site that we are missing. ## Lnswap -[LNSWAP](https://www.lnswap.org). Non custiodial crypto currency exchange Non custiodial crypto currency exchange +[LNSWAP](https://www.lnswap.org). Non-custodial crypto currency exchange ![](/img/sh_lnswap.png) @@ -41,4 +41,3 @@ Please edit this page to add any relevant new site that we are missing. [Stackswap](https://app.stackswap.org/v2) ![](/img/sh_stackswap.png) - diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/more.md b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/more.md index a7b57f922c..1e14b9a5a5 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/more.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/more.md @@ -8,7 +8,7 @@ List of sites on alphabetical order added by the community. :::tip Are we missing one? Please edit this page to add any relevant new site that we are missing. -::: Please edit this page to add any relevant new site that we are missing. ::: +::: ## Citycoins @@ -18,6 +18,6 @@ Please edit this page to add any relevant new site that we are missing. ## Sigle -[Sigle](https://www.sigle.io/) is a decentralised and open source web 3 writing platform. +[Sigle](https://www.sigle.io/) is a decentralized and open source web 3 writing platform. -![](/img/sh_sigle.png) \ No newline at end of file +![](/img/sh_sigle.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md index 6f1f8ecfa0..d582604854 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/nft.md @@ -8,23 +8,32 @@ List of sites that operate NFTS on Stacks on alphabetical order. :::tip Are we missing one? Please edit this page to add any relevant new site that we are missing. -::: Please edit this page to add any relevant new site that we are missing. ::: +::: ### [Byzantion](https://byzantion.xyz/) ![website-screenshot](/img/sh_nft_byzantion.png) ### [Gamma](https://gamma.io/) + ![website-screenshot](/img/sh_nft_gamma.png) ### [Megapont](https://www.megapont.com/) ![website-screenshot](/img/sh_nft_megapont.png) +### [Satoshibles](https://satoshibles.com/) + +![website-screenshot](/img/sh_nft_satoshibles.png) + ### [StacksArt](https://www.stacksart.com/) ![website-screenshot](/img/sh_nft_stacksart.png) +### [StacksBridge](https://stacksbridge.com/) + +![website-screenshot](/img/sh_nft_stacksbridge.png) + ### [Superfandom](https://superfandom.io/) -![website-screenshot](/img/sh_superfandom.png) \ No newline at end of file +![website-screenshot](/img/sh_superfandom.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md index 9618006777..54f6823e33 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/stacks-info-sites.md @@ -8,7 +8,7 @@ A list of sites on alphabetical order that display status and stats of the Stack :::tip Are we missing one? Please edit this page to add any relevant new site that we are missing. -::: Please edit this page to add any relevant new site that we are missing. ::: +::: ### [Haystack](https://haystack.tools/mempool) @@ -30,7 +30,7 @@ Please edit this page to add any relevant new site that we are missing. ![website-screenshot](/img/sh_stxstats.png) -### [Novuminsights](https://stacks.novuminsights.com/health) +### [Novum Insights](https://stacks.novuminsights.com/health) ![website-screenshot](/img/sh_novuminsights.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md index fb1bf958be..80142a29d1 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/services-using-stacks/wallets.md @@ -8,13 +8,14 @@ A list of hardware and software wallets for Stacks :::tip Are we missing one? Please edit this page to add any relevant new site that we are missing. -::: Please edit this page to add any relevant new site that we are missing. ::: +::: ## Blockchain.com [Blockchain.com](https://www.blockchain.com/wallet) ![](/img/sh_blockchain.png) + ## Boom [Boom](https://boom.money) @@ -26,18 +27,13 @@ Please edit this page to add any relevant new site that we are missing. [D'CENT](https://dcentwallet.com) ![](/img/sh_dcent.png) + ## Hiro Wallet [Hiro Wallet](https://www.hiro.so/wallet) ![](/img/sh_hirowallet.png) -## Neptune - -[Neptune](https://neptunewallet.io) - -![](/img/sh_neptunewallet.png) - ## Xverse [Xverse](https://www.xverse.app/) @@ -48,4 +44,4 @@ Please edit this page to add any relevant new site that we are missing. [Wise](https://wiseapp.id) -![](/img/sh_wiseapp.png) \ No newline at end of file +![](/img/sh_wiseapp.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md new file mode 100644 index 0000000000..8942535ac4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/accounts.md @@ -0,0 +1,217 @@ +--- +title: Accounts +description: Guide to Stacks 2.0 accounts +sidebar_position: 7 +--- + +## Introduction + +Stacks 2.0 accounts are entities that own assets, like Stacks (STX) tokens. An account has an address, private key, nonce, and one or more asset balances. An account has an address, private key, nonce, and one or more asset balances. An account has an address, private key, nonce, and one or more asset balances. An account has an address, private key, nonce, and one or more asset balances. + +:::tip The encryption algorithm used in Stacks 2.0 is **[secp256k1](https://en.bitcoinwiki.org/wiki/Secp256k1)**. + +Additionally, [Ed25519](https://ed25519.cr.yp.to/) is also used just for the VRF (Verifiable Random Function). ::: + +Assets cannot leave an account without an action from the account owner. Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. Assets cannot leave an account without an action from the account owner. All changes to assets (and the balances of the account) require a corresponding transaction. + +:::tip +The transaction type doesn't need to be a token transfer - contract deploy and contract call transactions can change the balances of an account +::: + +## Creation + +An account is generated from a 24-word mnemonic phrase. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. This is often referred to as the **seed phrase**. The seed phrase provides access to Stacks 2.0 accounts. + +:::danger +If the seed phrase is lost, access to the associated account cannot be restored. No person or organization, including Blockstack, can recover a lost seed phrase. +::: No person or organization, including Blockstack, can recover a lost seed phrase. +::: No person or organization can recover a lost seed phrase. +::: + +The easiest way to generate a new Stacks 2.0 account is to use the [Stacks CLI](https://github.com/hirosystems/stacks.js/tree/master/packages/cli): + +```bash +# install CLI globally +npm install --global @stacks/cli + +# generate a new account and store details in a new file +# '-t' option makes this a testnet account +stx make_keychain -t > cli_keychain.json +``` + +`make_keychain` creates the following file: + +```js +{ + "mnemonic": "aaa bbb ccc ddd ...", + "keyInfo": { + "privateKey": "5a3f1f15245bb3fb...", + "address": "STJRM2AMVF90ER6G3RW1QTF85E3HZH37006D5ER1", + "btcAddress": "biwSd6KTEvJcyX2R8oyfgj5REuLzczMYC1", + "wif": "L4HXn7PLmzoNW...", + "index": 0 + } +} +``` + +:::tip Check out the [Stacks CLI reference](https://docs.hiro.so/references/stacks-cli) for more details ::: + +| Field | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mnemonic` | A 24-word seed phrase used to access the account, generated using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) with 256 bits of entropy | +| `keyInfo.privateKey` | Private key for the account. Private key for the account. Private key for the account. Private key for the account. Required for token transfers and often referred to as `senderKey` | +| `keyInfo.address` | Stacks address for the account | +| `keyInfo.btcAddress` | Corresponding BTC address for the account. | +| `keyInfo.wif` | Private key of the btcAddress in compressed format. | +| `keyInfo.index` | Nonce for the account, starting at 0 | + +Note that a new account automatically exists for each new private key. Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. Note that a new account automatically exists for each new private key. Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. Note that a new account automatically exists for each new private key. There is no need to manually instantiate an account on the Stacks 2.0 blockchain. + +:::tip Addresses are created by generating the [RIPEMD-160 hash](https://en.wikipedia.org/wiki/RIPEMD#RIPEMD-160_hashes) of the [SHA256](https://en.bitcoinwiki.org/wiki/SHA-256) of the public key. BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: BTC addresses are encoded with [Base58Check](https://en.bitcoin.it/wiki/Base58Check_encoding). For Stacks addresses, [c32check](https://github.com/stacks-network/c32check) is used. Deriving an address from a public key can be done without internet access, for instance using the c32check `c32addressDecode` method. ::: + +Alternatively to the CLI creation, the [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library can be used: + +```js +import { + makeRandomPrivKey, + privateKeyToString, + getAddressFromPrivateKey, + TransactionVersion, + getPublicKey, +} from "@stacks/transactions"; + +const privateKey = makeRandomPrivKey(); + +// Get public key from private +const publicKey = getPublicKey(privateKey); + +const stacksAddress = getAddressFromPrivateKey( + privateKeyToString(privateKey), + TransactionVersion.Testnet // remove for Mainnet addresses +); +``` + +A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. A second alternative would be to use [stacks-gen](https://github.com/psq/stacks-gen). This tool will generate all the keys you need in one place, including the values needed for calling the stacking contract, and also a WIF key for use with `bitcoind`. + +#### stacks-gen prerequisite + +Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). Install [npx](https://github.com/npm/npx) if not already installed. (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). (npx will check whether `` exists in \$PATH, or in the local project binaries, and execute that. If `` is not found, it will be installed prior to execution). If `` is not found, it will be installed prior to execution). + +``` +npm install -g npx +``` + +#### stacks-gen usage + +``` +npx -q stacks-gen sk --testnet + +{ + "phrase": "guide air pet hat friend anchor harvest dog depart matter deny awkward sign almost speak short dragon rare private fame depart elevator snake chef", + "private": "0351764dc07ee1ad038ff49c0e020799f0a350dd0769017ea09460e150a6401901", + "public": "022d82baea2d041ac281bebafab11571f45db4f163a9e3f8640b1c804a4ac6f662", + "stacks": "ST16JQQNQXVNGR8RZ1D52TMH5MFHTXVPHRV6YE19C", + "stacking": "{ hashbytes: 0x4d2bdeb7eeeb0c231f0b4a2d5225a3e3aeeed1c6, version: 0x00 }", + "btc": "mnYzsxxW271GkmyMnRfiopEkaEpeqLtDy8", + "wif": "cMh9kwaCEttgTQYkyMUYQVbdm5ZarZdBHErcq7mXUChXXCo7CFEh" +} +``` + +:::tip The stacking object with hashbytes and a version represents the bitcoin address derived from the Stacks address. Read more about the [bitcoin address format](stacking#bitcoin-address). ::: Read more about the [bitcoin address format](stacking#bitcoin-address). ::: Read more about the [bitcoin address format](stacking#bitcoin-address). ::: + +Full documentation available at [stacks-gen](https://github.com/psq/stacks-gen). + +## Querying + +### Get Stacks (STX) balance and nonce + +STX balance and nonce can be obtained through the [`GET /v2/accounts/`](https://docs.hiro.so/api#operation/get_account_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/accounts/' +``` + +Sample response: + +```js +{ + "balance": "0x0000000000000000002386f26f3f40ec", + "nonce": 17 +} +``` + +:::tip +The balance string represents an unsigned 128-bit integer (big-endian) in hex encoding +::: + +### Get all token balances + +All token balances can be obtained through the [`GET /extended/v1/address//balances`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//balances' +``` + +Sample response: + +```js +{ + "stx": { + "balance": "0", + "total_sent": "0", + "total_received": "0" + }, + "fungible_tokens": {}, + "non_fungible_tokens": {} +} +``` + +:::tip Stacks accounts cannot hold bitcoins. -> Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: -> Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: -> Stacks accounts cannot hold bitcoins. The best way to obtain corresponding BTC balances is to derive the BTC address from the Stacks address (using [`c32check`](https://github.com/stacks-network/c32check#c32tob58-b58toc32)) and query the Bitcoin network. ::: + +### Get all asset events + +All asset events associated with the account can be obtained through the [`GET /extended/v1/address//assets`](https://docs.hiro.so/api#operation/get_account_balance) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/address//assets' +``` + +Sample response: + +```js +{ + "limit": 20, + "offset": 0, + "total": 0, + "results": [ + { + "event_index": 5, + "event_type": "non_fungible_token_asset", + "asset": { + "asset_event_type": "transfer", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::hello-nft", + "sender": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "recipient": "SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G", + "value": { + "hex": "0x0100000000000000000000000000000001", + "repr": "u1" + } + } + }, + { + "event_index": 3, + "event_type": "fungible_token_asset", + "asset": { + "asset_event_type": "mint", + "asset_id": "ST2W14YX9SFVDB1ZGHSH40CX1YQAP9XKRAYSSVYAG.hello_world::novel-token-19", + "sender": "", + "recipient": "SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR", + "amount": "12" + } + } + ] +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md new file mode 100644 index 0000000000..4683ae5eef --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/authentication.md @@ -0,0 +1,63 @@ +--- +title: Authentication +description: Register and sign in users with identities on the Stacks blockchain +sidebar_position: 8 +--- + +## Introduction + +This guide explains how authentication is performed on the Stacks blockchain. + +Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. Authentication provides a way for users to identify themselves to an app while retaining complete control over their credentials and personal details. It can be integrated alone or used in conjunction with [transaction signing](https://docs.hiro.so/get-started/transactions#signature-and-verification) and [data storage](https://docs.stacks.co/build-apps/references/gaia), for which it is a prerequisite. + +Users who register for your app can subsequently authenticate to any other app with support for the [Blockchain Naming System](bns) and vice versa. + +## How it works + +The authentication flow with Stacks is similar to the typical client-server flow used by centralized sign in services (for example, OAuth). However, with Stacks the authentication flow happens entirely client-side. However, with Stacks the authentication flow happens entirely client-side. However, with Stacks the authentication flow happens entirely client-side. However, with Stacks the authentication flow happens entirely client-side. + +An app and authenticator, such as [the Stacks Wallet](https://www.hiro.so/wallet/install-web), communicate during the authentication flow by passing back and forth two tokens. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. The requesting app sends the authenticator an `authRequest` token. Once a user approves authentication, the authenticator responds to the app with an `authResponse` token. + +These tokens are based on [a JSON Web Token (JWT) standard](https://tools.ietf.org/html/rfc7519) with additional support for the `secp256k1` curve used by Bitcoin and many other cryptocurrencies. They are passed via URL query strings. + +When a user chooses to authenticate an app, it sends the `authRequest` token to the authenticator via a URL query string with an equally named parameter: + +`https://wallet.hiro.so/...?authRequest=j902120cn829n1jnvoa...` + +When the authenticator receives the request, it generates an `authResponse` token for the app using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. The ephemeral transit key is just used for the particular instance of the app, in this case, to sign the `authRequest`. + +The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. The public portion of the transit key is passed in the `authRequest` token. The app stores the ephemeral transit key during request generation. The public portion of the transit key is passed in the `authRequest` token. The authenticator uses the public portion of the key to encrypt an _app private key_ which is returned via the `authResponse`. + +The authenticator generates the app private key from the user's _identity address private key_ and the app's domain. The app private key serves three functions: The app private key serves three functions: The app private key serves three functions: The app private key serves three functions: + +1. It is used to create credentials that give the app access to a storage bucket in the user's Gaia hub +2. It is used in the end-to-end encryption of files stored for the app in the user's Gaia storage. +3. It serves as a cryptographic secret that apps can use to perform other cryptographic functions. + +Finally, the app private key is deterministic, meaning that the same private key will always be generated for a given Stacks address and domain. + +The first two of these functions are particularly relevant to [data storage with Stacks.js](https://docs.stacks.co/docs/gaia). + +## Key pairs + +Authentication with Stacks makes extensive use of public key cryptography generally and ECDSA with the `secp256k1` curve in particular. + +The following sections describe the three public-private key pairs used, including how they're generated, where they're used and to whom private keys are disclosed. + +### Transit private key + +The transit private is an ephemeral key that is used to encrypt secrets that need to be passed from the authenticator to the app during the authentication process. It is randomly generated by the app at the beginning of the authentication response. It is randomly generated by the app at the beginning of the authentication response. It is randomly generated by the app at the beginning of the authentication response. It is randomly generated by the app at the beginning of the authentication response. + +The public key that corresponds to the transit private key is stored in a single element array in the `public_keys` key of the authentication request token. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. The authenticator encrypts secret data such as the app private key using this public key and sends it back to the app when the user signs in to the app. The transit private key signs the app authentication request. + +### Identity address private key + +The identity address private key is derived from the user's keychain phrase and is the private key of the Stacks username that the user chooses to use to sign in to the app. It is a secret owned by the user and never leaves the user's instance of the authenticator. It is a secret owned by the user and never leaves the user's instance of the authenticator. It is a secret owned by the user and never leaves the user's instance of the authenticator. It is a secret owned by the user and never leaves the user's instance of the authenticator. + +This private key signs the authentication response token for an app to indicate that the user approves sign in to that app. + +### App private key + +The app private key is an app-specific private key that is generated from the user's identity address private key using the `domain_name` as input. + +The app private key is securely shared with the app on each authentication, encrypted by the authenticator with the transit public key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. Because the transit key is only stored on the client side, this prevents a man-in-the-middle attack where a server or internet provider could potentially snoop on the app private key. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/bns.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/bns.md new file mode 100644 index 0000000000..b7de38b8a8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/bns.md @@ -0,0 +1,276 @@ +--- +title: Bitcoin Name System +description: Binds Stacks usernames to off-chain state +sidebar_position: 8 +--- + +Bitcoin Name System (BNS) is a network system that binds Stacks usernames to off-chain state without relying on any central points of control. + +The Stacks V1 blockchain implemented BNS through first-order name operations. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. In Stacks V2, BNS is instead implemented through a smart-contract loaded during the genesis block. + +Names in BNS have three properties: + +- **Names are globally unique.** The protocol does not allow name collisions, and all well-behaved nodes resolve a given name to the same state. +- **Names are human-meaningful.** Each name is chosen by its creator. +- **Names are strongly owned.** Only the name's owner can change the state it resolves to. Specifically, a name is owned by one or more ECDSA private keys. Specifically, a name is owned by one or more ECDSA private keys. Specifically, a name is owned by one or more ECDSA private keys. Specifically, a name is owned by one or more ECDSA private keys. + +The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. The Stacks blockchain insures that each node's BNS view is synchronized to all of the other nodes in the world, so queries on one node will be the same on other nodes. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. Stacks blockchain nodes allow a name's owner to bind up to 40Kb of off-chain state to their name, which will be replicated to all other Stacks blockchain nodes via a P2P network. + +The biggest consequence for developers is that in BNS, reading name state is fast and cheap but writing name state is slow and expensive. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. This is because registering and modifying names requires one or more transactions to be sent to the underlying blockchain, and BNS nodes will not process them until they are sufficiently confirmed. Users and developers need to acquire and spend the requisite cryptocurrency (STX) to send BNS transactions. + +## Motivation behind name systems + +We rely on name systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's name system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. We rely on naming systems in everyday life, and they play a critical role in many different applications. For example, when you look up a friend on social media, you are using the platform's naming system to resolve their name to their profile. When you look up a website, you are using the Domain Name Service to resolve the hostname to its host's IP address. When you check out a Git branch, you are using your Git client to resolve the branch name to a commit hash. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. When you look up someone's PGP key on a keyserver, you are resolving their key ID to their public key. + +What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. What kinds of things do we want to be true about names? In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. In BNS, names are globally unique, names are human-meaningful, and names are strongly owned. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. However, if you look at these examples, you'll see that each of them only guarantees _two_ of these properties. This limits how useful they can be. + +- In DNS and social media, names are globally unique and human-readable, but not strongly owned. The system operator has the final say as to what each names resolves to. The system operator has the final say as to what each names resolves to. The system operator has the final say as to what each names resolves to. The system operator has the final say as to what each names resolves to. + + - **Problem**: Clients must trust the system to make the right choice in what a given name resolves to. This includes trusting that no one but the system administrators can make these changes. This includes trusting that no one but the system administrators can make these changes. This includes trusting that no one but the system administrators can make these changes. This includes trusting that no one but the system administrators can make these changes. + +- In Git, branch names are human-meaningful and strongly owned, but not globally unique. In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. In Git, branch names are human-meaningful and strongly owned, but not globally unique. Two different Git nodes may resolve the same branch name to different unrelated repository states. + + - **Problem**: Since names can refer to conflicting state, developers have to figure out some other mechanism to resolve ambiguities. In Git's case, the user has to manually intervene. In Git's case, the user has to manually intervene. In Git's case, the user has to manually intervene. In Git's case, the user has to manually intervene. + +- In PGP, names are key IDs. They are are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. They are are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. They are are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. They are globally unique and cryptographically owned, but not human-readable. PGP key IDs are derived from the keys they reference. + - **Problem**: These names are difficult for most users to remember since they do not carry semantic information relating to their use in the system. + +BNS names have all three properties, and none of these problems. This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: This makes it a powerful tool for building all kinds of network applications. With BNS, we can do the following and more: + +- Build domain name services where hostnames can't be hijacked. +- Build social media platforms where user names can't be stolen by phishers. +- Build version control systems where repository branches do not conflict. +- Build public-key infrastructure where it's easy for users to discover and remember each other's keys. + +## Organization of BNS + +BNS names are organized into a global name hierarchy. There are three different layers in this hierarchy related to naming: There are three different layers in this hierarchy related to naming: There are three different layers in this hierarchy related to naming: There are three different layers in this hierarchy related to naming: + +- **Namespaces**. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. These are the top-level names in the hierarchy. An analogy to BNS namespaces are DNS top-level domains. Existing BNS namespaces include `.id`, `.podcast`, and `.helloworld`. All other names belong to exactly one namespace. Anyone can create a namespace, but in order for the namespace to be persisted, it must be _launched_ so that anyone can register names in it. Namespaces are not owned by their creators. + +- **BNS names**. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. These are names whose records are stored directly on the blockchain. The ownership and state of these names are controlled by sending blockchain transactions. Example names include `verified.podcast` and `muneeb.id`. Anyone can create a BNS name, as long as the namespace that contains it exists already. + +- **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. + +A feature comparison matrix summarizing the similarities and differences between these name objects is presented below: + +| Feature | **Namespaces** | **BNS names** | **BNS Subdomains** | +| -------------------------------------- | -------------- | ------------- | ------------------ | +| Globally unique | X | X | X | +| Human-meaningful | X | X | X | +| Owned by a private key | | X | X | +| Anyone can create | X | X | [1] | +| Owner can update | | X | [1] | +| State hosted on-chain | X | X | | +| State hosted off-chain | | X | X | +| Behavior controlled by consensus rules | X | X | | +| May have an expiration date | | X | | + +[1] Requires the cooperation of a BNS name owner to broadcast its transactions + +## Namespaces + +Namespaces are the top-level name objects in BNS. + +They control a few properties about the names within them: + +- How expensive they are to register +- How long they last before they have to be renewed +- Who (if anyone) receives the name registration fees +- Who is allowed to seed the namespace with its initial names. + +At the time of this writing, by far the largest BNS namespace is the `.id` namespace. Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered unspendable (the intention is to discourage ID squatters). Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered unspendable (the intention is to discourage ID squatters). Names in the `.id` namespace are meant for resolving user identities. Short names in `.id` are more expensive than long names, and have to be renewed by their owners every two years. Name registration fees are not paid to anyone in particular---they are instead sent to a "black hole" where they are rendered non-spendable (the intention is to discourage ID squatters). + +Unlike DNS, _anyone_ can create a namespace and set its properties. Namespaces are created on a first-come first-serve basis, and once created, they last forever. Namespaces are created on a first-come first-serve basis, and once created, they last forever. Namespaces are created on a first-come first-serve basis, and once created, they last forever. Namespaces are created on a first-come first-serve basis, and once created, they last forever. + +However, creating a namespace is not free. However, creating a namespace is not free. The namespace creator must _burn_ cryptocurrency to do so. The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). The shorter the namespace, the more cryptocurrency must be burned (that is, short namespaces are more valuable than long namespaces). For example, it cost Blockstack PBC 40 BTC to create the `.id` namespace in 2015 (in transaction `5f00b8e609821edd6f3369ee4ee86e03ea34b890e242236cdb66ef6c9c6a1b281`). + +Namespaces can be between 1 and 19 characters long, and are composed of the characters `a-z`, `0-9`, `-`, and `_`. + +## Subdomains + +BNS names are strongly owned because the owner of its private key can generate valid transactions that update its zone file hash and owner. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. However, this comes at the cost of requiring a name owner to pay for the underlying transaction in the blockchain. Moreover, this approach limits the rate of BNS name registrations and operations to the underlying blockchain's transaction bandwidth. + +BNS overcomes this with subdomains. A **BNS subdomain** is a type of BNS name whose state and owner are stored outside of the blockchain, but whose existence and operation history are anchored to the blockchain. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. **BNS subdomains**. These are names whose records are stored off-chain, but are collectively anchored to the blockchain. The ownership and state for these names lives within the P2P network data. While BNS subdomains are owned by separate private keys, a BNS name owner must broadcast their subdomain state. Example subdomains include `jude.personal.id` and `podsaveamerica.verified.podcast`. Unlike BNS namespaces and names, the state of BNS subdomains is _not_ part of the blockchain consensus rules. Like their on-chain counterparts, subdomains are globally unique, strongly owned, and human-readable. BNS gives them their own name state and public keys. Unlike on-chain names, subdomains can be created and managed cheaply, because they are broadcast to the BNS network in batches. A single blockchain transaction can send up to 120 subdomain operations. + +This is achieved by storing subdomain records in the BNS name zone files. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. An on-chain name owner broadcasts subdomain operations by encoding them as `TXT` records within a DNS zone file. To broadcast the zone file, the name owner sets the new zone file hash with a `NAME_UPDATE` transaction and replicates the zone file. This, in turn, replicates all subdomain operations it contains, and anchors the set of subdomain operations to an on-chain transaction. The BNS node's consensus rules ensure that only valid subdomain operations from _valid_ `NAME_UPDATE` transactions will ever be stored. + +For example, the name `verified.podcast` once wrote the zone file hash `247121450ca0e9af45e85a82e61cd525cd7ba023`, which is the hash of the following zone file: + +```bash +$TTL 3600 +1yeardaily TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxeWVhcmRhaWx5CiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMXllYXJkYWlseS9oZWFkLmpzb24iCg==" +2dopequeens TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAyZG9wZXF1ZWVucwokVFRMIDM2MDAKX2h0dHAuX3RjcCBVUkkgMTAgMSAiaHR0cHM6Ly9waC5kb3Rwb2RjYXN0LmNvLzJkb3BlcXVlZW5zL2hlYWQuanNvbiIK" +10happier TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMGhhcHBpZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMGhhcHBpZXIvaGVhZC5qc29uIgo=" +31thoughts TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMXRob3VnaHRzCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzF0aG91Z2h0cy9oZWFkLmpzb24iCg==" +359 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNTkKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8zNTkvaGVhZC5qc29uIgo=" +30for30 TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzMGZvcjMwCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzBmb3IzMC9oZWFkLmpzb24iCg==" +onea TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiBvbmVhCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vb25lYS9oZWFkLmpzb24iCg==" +10minuteteacher TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAxMG1pbnV0ZXRlYWNoZXIKJFRUTCAzNjAwCl9odHRwLl90Y3AgVVJJIDEwIDEgImh0dHBzOi8vcGguZG90cG9kY2FzdC5jby8xMG1pbnV0ZXRlYWNoZXIvaGVhZC5qc29uIgo=" +36questionsthepodcastmusical TXT "owner=1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH" "seqn=0" "parts=1" "zf0=JE9SSUdJTiAzNnF1ZXN0aW9uc3RoZXBvZGNhc3RtdXNpY2FsCiRUVEwgMzYwMApfaHR0cC5fdGNwIFVSSSAxMCAxICJodHRwczovL3BoLmRvdHBvZGNhc3QuY28vMzZxdWVzdGlvbnN0aGVwb2RjYXN0bXVzaWNhbC9oZWFkLmpzb24iCg==" +_http._tcp URI 10 1 "https://dotpodcast.co/" +``` + +Each `TXT` record in this zone file encodes a subdomain-creation. For example, `1yeardaily.verified.podcast` resolves to: For example, `1yeardaily.verified.podcast` resolves to: For example, `1yeardaily.verified.podcast` resolves to: For example, `1yeardaily.verified.podcast` resolves to: + +```json +{ + "address": "1MwPD6dH4fE3gQ9mCov81L1DEQWT7E85qH", + "blockchain": "bitcoin", + "last_txid": "d87a22ebab3455b7399bfef8a41791935f94bc97aee55967edd5a87f22cce339", + "status": "registered_subdomain", + "zonefile_hash": "e7acc97fd42c48ed94fd4d41f674eddbee5557e3", + "zonefile_txt": "$ORIGIN 1yeardaily\n$TTL 3600\n_http._tcp URI 10 1 \"https://ph.dotpodcast.co/1yeardaily/head.json\"\n" +} +``` + +This information was extracted from the `1yeardaily` `TXT` resource record in the zone file for `verified.podcast`. + +### Subdomain Lifecycle + +Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. Note that `1yeardaily.verified.podcast` has a different public key hash (address) than `verified.podcast`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. A BNS node will only process a subsequent subdomain operation on `1yeardaily.verified.podcast` if it includes a signature from this address's private key. `verified.podcast` cannot generate updates; only the owner of `1yeardaily.verified.podcast can do so`. + +The lifecycle of a subdomain and its operations is shown in Figure 2. + +``` + subdomain subdomain subdomain + creation update transfer ++----------------+ +----------------+ +----------------+ +| cicero | | cicero | | cicero | +| owner="1Et..." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +The subdomain-creation and subdomain-transfer transactions for +"cicero.res_publica.id" are broadcast by the owner of "res_publica.id." +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." | signed | owner="1Et..." | signed | owner="1cJ..." | +| zf0="7e4..." |<--------| zf0="111..." |<--------| zf0="111..." |<---- ... +| seqn=0 | | seqn=1 | | seqn=2 | +| | | sig="xxxx" | | sig="xxxx" | ++----------------+ +----------------+ +----------------+ + | | | + | off-chain | | +~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | ~ ~ ~ ~ ~ ~ ~ ... + | on-chain | | + V V (zone file hash ) V ++----------------+ +----------------+ +----------------+ +| res_publica.id | | jude.id | | res_publica.id | +| NAME_UPDATE |<--------| NAME_UPDATE |<--------| NAME_UPDATE |<---- ... ++----------------+ +----------------+ +----------------+ + blockchain blockchain blockchain + block block block + + +Figure 2: Subdomain lifetime with respect to on-chain name operations .A new +subdomain operation will only be accepted if it has a later "sequence=" number, +and a valid signature in "sig=" over the transaction body .The "sig=" field +includes both the public key and signature, and the public key must hash to +the previous subdomain operation's "addr=" field. + +A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of cicero.res_publica.id needs the owner of res_publica.id to broadcast a subdomain-transfer transaction to change cicero.res_publica.id's public key. +needs the owner of res_publica.id to broadcast a subdomain-transfer transaction to change cicero.res_publica.id's public key. +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." + +``` + needs the owner of res_publica.id to broadcast a subdomain-transfer transaction to change cicero.res_publica.id's public key. +needs the owner of res_publica.id to broadcast a subdomain-transfer transaction to change cicero.res_publica.id's public key. +However, any on-chain name ("jude.id" in this case) can broadcast a subdomain +update for "cicero.res_publica.id." + + + +Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: Subdomain operations are ordered by sequence number, starting at 0. Each new subdomain operation must include: Each new subdomain operation must include: + +- The next sequence number +- The public key that hashes to the previous subdomain transaction's address +- A signature from the corresponding private key over the entire subdomain operation. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. Invalid subdomain operations are ignored. Invalid subdomain operations are ignored. + +If two correctly signed but conflicting subdomain operations are discovered (that is, they have the same sequence number), the one that occurs earlier in the blockchain's history is accepted. Invalid subdomain operations are ignored. Invalid subdomain operations are ignored. Invalid subdomain operations are ignored. + +### Subdomain Creation and Management + +That said, to create a subdomain, the subdomain owner generates a subdomain-creation operation for their desired name and gives it to the on-chain name owner. In particular: + +- A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. A subdomain-creation transaction can only be processed by the owner of the on-chain name that shares its suffix. For example, only the owner of `res_publica.id` can broadcast subdomain-creation transactions for subdomain names ending in `.res_publica.id`. +- A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. A subdomain-transfer transaction can only be broadcast by the owner of the on-chain name that created it. For example, the owner of `cicero.res_publica.id` needs the owner of `res_publica.id` to broadcast a subdomain-transfer transaction to change `cicero.res_publica.id`'s public key. +- In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. In order to send a subdomain-creation or subdomain-transfer, all of an on-chain name owner's zone files must be present in the Atlas network. This lets the BNS node prove the _absence_ of any conflicting subdomain-creation and subdomain-transfer operations when processing new zone files. +- A subdomain update transaction can be broadcast by _any_ on-chain name owner, but the subdomain owner needs to find one who will cooperate. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. For example, the owner of `verified.podcast` can broadcast a subdomain-update transaction created by the owner of `cicero.res_publica.id`. + +Unlike an on-chain name, a subdomain owner needs an on-chain name owner's help to broadcast their subdomain operations. In particular: In particular: In particular: + +Once created, a subdomain owner can use any on-chain name owner to broadcast a subdomain-update operation. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. To do so, they generate and sign the requisite subdomain operation and give it to an on-chain name owner, who then packages it with other subdomain operations into a DNS zone file and broadcasts it to the network. + +If the subdomain owner wants to change the address of their subdomain, they need to sign a subdomain-transfer operation and give it to the on-chain name owner who created the subdomain. They then package it into a zone file and broadcast it. They then package it into a zone file and broadcast it. They then package it into a zone file and broadcast it. They then package it into a zone file and broadcast it. + +### Subdomain Registrars + +Because subdomain names are cheap, developers may be inclined to run subdomain registrars on behalf of their applications. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. For example, the name `personal.id` is used to register usernames without requiring them to spend any Bitcoin. + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +## BNS and DID Standards + +We supply a reference implementation of a [BNS Subdomain Registrar](https://github.com/stacks-network/subdomain-registrar) to help developers broadcast subdomain operations. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. Users would still own their subdomain names; the registrar simply gives developers a convenient way for them to register and manage them in the context of a particular application. + +Each name in BNS has an associated DID. The DID format for BNS is: Each name in BNS has an associated DID. The DID format for BNS is: The DID format for BNS is: Each name in BNS has an associated DID. The DID format for BNS is: The DID format for BNS is: + +```bash + did:stack:v0:{address}-{index} +``` + +Where: + +- `{address}` is an on-chain public key hash (for example a Bitcoin address). +- `{index}` refers to the `nth` name this address created. + +For example, the DID for `personal.id` is `did:stack:v0:1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV-0`, because the name `personal.id` was the first-ever name created by `1dARRtzHPAFRNE7Yup2Md9w18XEQAtLiV`. + +As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). + +The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. The public key may change, but the DID will not. The purpose of a DID is to provide an eternal identifier for a public key. The public key may change, but the DID will not. The public key may change, but the DID will not. + +Stacks Blockchain implements a DID method of its own in order to be compatible with other systems that use DIDs for public key resolution. In order for a DID to be resolvable, all of the following must be true for a name: In order for a DID to be resolvable, all of the following must be true for a name: In order for a DID to be resolvable, all of the following must be true for a name: In order for a DID to be resolvable, all of the following must be true for a name: + +- The name must exist +- The name's zone file hash must be the hash of a well-formed DNS zone file +- The DNS zone file must be present in the Stacks node's data. +- The DNS zone file must contain a `URI` resource record that points to a signed JSON Web Token +- The public key that signed the JSON Web Token (and is included with it) must hash to the address that owns the name + +Not all names will have DIDs that resolve to public keys. However, names created by standard tooling will have DIDs that do. However, names created by standard tooling will have DIDs that do. However, names created by standard tooling will have DIDs that do. However, names created by standard tooling will have DIDs that do. + +A RESTful API is under development. + +## DID Encoding for Subdomains + +Every name and subdomain in BNS has a DID. Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. Every name and subdomain in BNS has a DID. The encoding is slightly different for subdomains, so the software can determine which code-path to take. + +- For on-chain BNS names, the `{address}` is the same as the Bitcoin address that owns the name. Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). Currently, both version byte 0 and version byte 5 addresses are supported (that is, addresses starting with `1` or `3`, meaning `p2pkh` and `p2sh` addresses). + +- For off-chain BNS subdomains, the `{address}` has version byte 63 for subdomains owned by a single private key, and version byte 50 for subdomains owned by a m-of-n set of private keys. That is, subdomain DID addresses start with `S` or `M`, respectively. That is, subdomain DID addresses start with `S` or `M`, respectively. That is, subdomain DID addresses start with `S` or `M`, respectively. That is, subdomain DID addresses start with `S` or `M`, respectively. + +The `{index}` field for a subdomain's DID is distinct from the `{index}` field for a BNS name's DID, even if the same created both names and subdomains. As another example, the DID for `jude.id` is `did:stack:v0:16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg-1`. Here, the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` had created one earlier name in history prior to this one (which happens to be `abcdefgh123456.id`). However, `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` _also_ created `jude.statism.id` as its first subdomain name. The DID for `jude.statism.id` is `did:stack:v0:SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i-0`. Note that the address `SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i` encodes the same public key hash as the address `16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg` (the only difference between these two strings is that the first is base58check-encoded with version byte 0, and the second is encoded with version byte 63). diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md new file mode 100644 index 0000000000..eac3bf9091 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/btc-connection.md @@ -0,0 +1,237 @@ +--- +title: Bitcoin Connection +description: How Stacks is connected to Bitcoin +sidebar_position: 3 +--- + +At the very beginning of these docs, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself. + +That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? + +Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem its solving and how it actually does that. We'll dive deeper into some of these topics as we go through Stacks Academy, but it's good to get a high-level picture to bring everything together. + +This topic is a bit of a rabbit hole, and this section of Stacks Academy is pretty long, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. + +Let's get into it. + +## Is Stacks a Bitcoin L2? + +Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. + +The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt article](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). + +The upcoming planned release of Stacks, called the Nakamoto release (convention to use names of famous Computer Scientists for major releases), will no longer have a separate security budget from Bitcoin. Instead, a 100% of Bitcoin hashpower will determine finality on Stacks layer. After the next upgrade, to reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). More details in the [Stacks paper](https://stacks.co/stacks.pdf). + +The definition of [L2 used in Ethereum](https://ethereum.org/en/layer-2/) and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. + +Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: + +1. Bitcoin finality, as discussed above, where 100% of the Bitcoin hashpower decides block ordering and transaction finality. +2. Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. +3. With the upcoming decentralized Bitcoin peg, called sBTC (see [sBTC paper](https://stacks.co/sbtc.pdf)), most of economy on Stacks layer will likely use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. +4. All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin L1. This compact storage of hashes on L1 is somewhat similar to rollups (although there are other differences). +5. Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. + +Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons why this question comes up often: + +1. The initial version of Stacks (released early 2021) had a separate security budget which changed to following 100% Bitcoin hashpower with the Nakamoto release. There is old material and blog posts floating around that still talk about the initial Stacks version. The old materials will likely get updated with time. +2. According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing a L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. +3. Bitcoin community members are generally skeptical of claims and on a look out for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good [Twitter thread](https://twitter.com/lopp/status/1623756872976158722?s=20) about his topic as well. + +Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. + +The TLDR is that it is better to refer to Stacks as a Bitcoin layer (the more generic term). However, the Bitcoin L2 term is more organic and simpler for users and we'll likely keep seeing the use of it. If the Bitcoin L2 term comes up then it's important to understand the technical differences and that unlike Ethereum L2s withdrawing BTC from Stacks requires signatures from peg-out signers. + +## Stacks Among Other Bitcoin Layers + +Let's take a look at how Stacks compares to some of the other Bitcoin layering solutions. This is a fresh and rapidly evolving ecosystem, so there are quite a few interesting approaches in the works. + +### Lightning + +Lightning is probably the most well-known Bitcoin layer, and is primarily designed to address scalability issues. Lightning functions as a separate P2P network from Bitcoin, allowing participants to conduct move their BTC from the main chain to Lightning, conduct multiple transactions on Lightning, and then send the final result to the BTC chain where it is finalized. + +This is actually a completely separate problem from what Stacks is trying to address. Where Lightning takes the existing functionality of Bitcoin and makes it much more scalable, Stacks is seeking to expand Bitcoin's functionality to do things you can't do now. + +Crucially, Lightning is ephemeral, meaning it has no state management. There is no continuous record of what has happened on the Lightning network, only current channels. Once users close their channel and their transactions are written back to the Bitcoin chain, they are gone. + +A key component of full-expressive smart contracts is that they maintain a permanent historical record of all transactions that have happened on the chain. + +Bitcoin does this now, but its scripting language is very limited. So where Lightning seeks to make existing Bitcoin functionality happen faster, Stacks seeks to add new functionality. + +### RSK + +Like Stacks, [RSK](https://www.rsk.co/) seeks to add additional functionality to Bitcoin, but it goes about that process differently than Stacks. + +RSK is a merge-mined chain, meaning that it is mined concurrently with Bitcoin. Stacks has its own miners and mining process, and its own economic value and security that is a function of that token value, more on this below. + +There are multiple perspectives to look at this from. Because RSK is merge-mined, Bitcoin miners are also the ones mining RSK blocks, and RSK does not have its own token. + +RSK can only exist with opt-in from Bitcoin miners and mining rewards are highly dependent on transaction volume. + +This also opens up a wider discussion on the costs and benefits of having a separate token, which we'll get into below. + +RSK is also EVM-compatible, where Stacks uses Clarity and the Clarity VM. + +### Liquid + +[Liquid](https://liquid.net/) is a federated network focused on unlocking more advanced financial capabilities with Bitcoin. Being federated, Liquid is not an open network, and thus not decentralized. + +The Liquid consensus mechanism is managed by 15 functionaries, who handle the transaction processing and validating. Liquid also does not support general-purpose applications, but is solely focused on financial applications. + +This was a brief overview of these other Bitcoin projects, for another perspective, Hiro wrote an [excellent post](https://www.hiro.so/blog/building-on-bitcoin-project-comparison) comparing Stacks with other Bitcoin projects. + +### Bitcoin Rollups + +Rollups are an exciting development for scaling decentralized applications. There are many different types of rollups; they're broadly divided into ZK rollups and Optimistic rollups, although other classifications are also there (see [this overview](https://era.zksync.io/docs/dev/fundamentals/rollups.html#what-are-rollups)). + +Rollups are generally considered layer-2 (L2) technology that runs on top of a layer-1 blockchain like Bitcoin or Ethereum. A critical aspect of rollups is the trustless nature where logic running on the L1 chain can determine whether something that happened on the rollup was valid. This is not true for all types of rollups, and there is some fuzziness around exact definitions. [Sovereign rollups](https://blog.celestia.org/sovereign-rollup-chains/), for example, only use the underlying L1 for data availability (DA) and not for consensus. + +Most of the rollups work on Ethereum uses Ethereum L1 both as a data availability layer, and for consensus, i.e., the validity of rollup transactions is determined by logic running on Ethereum L1. Newer systems, [like Celestia](https://celestia.org/), are taking a more modular approach and are separating DA from consensus. One interesting aspect of separating DA is that more established and durable chains like Bitcoin can be used for DA as well. Below is an interesting comparison of sidechains and two types of rollups possible on Bitcoin (John Light posted this [on Twitter](https://twitter.com/lightcoin/status/1630301411962388481?s=20)): + +![Bitcoin rollups compared with other L2s](rollup-comparison.png) + +This image broadly means developers can build sovereign rollups on Bitcoin today, but you'll need a "trusted" setup for moving BTC in and out of the rollup. In fact, people are already doing this -- see the recent [Rollkit announcement](https://rollkit.dev/blog/sovereign-rollups-on-bitcoin/). To build validity rollups, meaning Bitcoin L1 enforces BTC withdrawals from the rollup, you'll need modifications to Bitcoin L1. See [this overview](https://bitcoinrollups.org/) for more details. + +#### How does the Stacks layer compare? + +Stacks is not really a sidechain, given the Nakamoto release (see [latest Stacks paper](https://stacks.co/stacks.pdf)), Stacks layer will achieve 100% Bitcoin finality. Also, the Stacks layer has various other direct connections to Bitcoin L1 that sidechains typically do not have -- see [the above section](#is-stacks-a-bitcoin-l2) for details if Stacks is a Bitcoin L2 or not; the short answer is it depends on the definition you use. + +Stacks with the Nakamoto release will have Bitcoin-grade reorg resistance. The Nakamoto release does not allow Stacks forks, which means that the Stacks chain does not fork on its own, follows Bitcoin blocks with 100% finality, and does not have a separate security budget. This means that once a Stacks transaction is finalized, it is at least as hard to re-org as a Bitcoin transaction. + +For data availability, Stacks publishes only hashes of data to Bitcoin every Bitcoin block instead of posting all the data to Bitcoin. The designers separate data validation from data availability. Bitcoin is used for data validation, which is important. Bitcoin L1 and only Bitcoin L1 can confirm whether a presented Stacks layer history is valid. The block data itself is kept outside of Bitcoin L1 for scalability. As long as STX has any market cap, there is an incentive for Stacks miners to keep copies of the Stacks layer ledger around. Even if a single copy of the Stacks ledger exists, it can be independently verified against Bitcoin L1. Sovereign rollups publish all data to Bitcoin L1, giving both Bitcoin-grade data validity and data availability. The potential downside is scalability at Bitcoin L1, but the hope is that rollup data will not become very large. + +#### Can Stacks layer work with rollups? + +Yes! There is already an active R&D effort to integrate rollups with the Stacks layer. Both with the Stacks layer and sovereign rollups the technically challenging part is how to get BTC in and out of the Stacks layer or the sovereign rollup. The decentralized BTC peg, see [the sBTC paper](https://stacks.co/sbtc.pdf), applies to both the Stacks layer and sovereign rollups. Without modifying Bitcoin L1, an sBTC-like design with a decentralized open-membership group of signers is the most trust-minimized way to move BTC in and out of Bitcoin layers. Once the necessary upgrades to Bitcoin L1 can be made to enable validity rollups i.e., Bitcoin L1 can enforce BTC withdrawal from a layer, then the Stacks layer can also upgrade to benefit from it. + +Given a trust-minimized asset like sBTC is needed for sovereign rollups, with the launch of sBTC such sovereign rollups become even more interesting to deploy. The Stacks layer can potentially provide the decentralized group of signers for a trust-minimized BTC asset that can be used in a sovereign rollup, and DA comes directly from Bitcoin L1 e.g., with Ordinals. If you want to learn more, please join the [sBTC working group](https://github.com/stacks-network/stacks/discussions/469). There might be a dedicated rollups working group in the Stacks project soon as well. + +## Why Does Stacks Need a Token? + +This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. + +Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. + +Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. + +The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure the chain. + +This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. + +Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. + +Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decided to have a separate token for Stacks L2? Great question! Let's dig into the details. + +The Stacks token (STX) is primarily meant to be used for two things (details in Stacks paper): + +1. Incentives for Stacks L2 miners +2. Incentives for peg-out signers + +The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionsless system. The only way to have a decentralized mining process is through incentives. As mentioned above, his is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. + +Similarly, the way the decentralized BTC peg, called sBTC (see the sBTC paper), is designed is that the group of signer is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. + +Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. + +## The Symbiotic Relationship Between Stacks and Bitcoin + +Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. + +But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. + +If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those [transactions become much more valuable](https://twitter.com/muneeb/status/1506976317618728963), increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. + + + + +## Reading from and Writing to Bitcoin + +One of the things that gives the Stacks chain its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. + +That's where [Clarity](../clarity/) comes in. Clarity is the smart contract language for Stacks, and is how we actually build out a lot of the functionality we are talking about here. + +### How Does Clarity Read BTC State? + +One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' [PoX mechanism](../stacks-academy/proof-of-transfer.md), every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the [`get-burn-block-info?` function](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#new-method-get-burn-block-info). + +This function allows us to pass in a Bitcoin block height and get back the header hash. The [`burn-block-height` Clarity keyword](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-keywords#burn-block-height) will give us the current block height of the Bitcoin chain. + +However, `get-burn-block-info?` only returns data of the Bitcoin block at that height if it has already been processed and was created after the launch of the Stacks chain. So if we want to evaluate whether or not something happened on Bitcoin, we have to wait at least one block later to do so. + +This is step 1 of Clarity contracts being able to serve as the programming layer for Bitcoin, when a BTC transaction is initiated, the first thing that needs to happen is that a Clarity contract needs to become aware of it. This can happen manually by utilizing Clarity functions discussed above with the [BTC library](https://explorer.stacks.co/txid/0x8b112f2b50c1fa864997b7496aaad1e3940700309a3fdcc6c07f1c6f8b9cfb7b?chain=mainnet), as [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html) do. + +:::tip +Note that this process is made easier by the additional Clarity functions added in 2.1, like the `get-burn-block-info?` function we looked at above. +::: + +Or we can automate (albeit at a cost of some centralization in our dapp) using an event-based architecture using something like Hiro's [chainhooks](https://www.hiro.so/blog/meet-4-new-features-in-clarinet#setting-up-trigger-actions-with-chainhooks), which will allow us to automatically trigger a Clarity contract call when a certain BTC transaction is initiated. + +This is the first component of using Stacks to build Bitcoin dapps, the read access to Bitcoin chain. + +### Can Clarity Write to BTC? + +But how can Stacks actually write to the Bitcoin chain? This has been somewhat of a holy grail problem in the Bitcoin and crypto world for years now, as it solves a difficult dilemma. + +On one hand, Bitcoin write functionality from more expressive smart contract chains allows for us to take the latent capital of Bitcoin and utilize it to build a Bitcoin-based economy. + +Bitcoin has a market cap of more than double that of Ethereum's, but has an almost non-existent app ecosystem because of this write problem. There is a massive market opportunity here for both developers and entrepreneurs if we are able to build decentralized applications that have a rival programming capacity to other chains like Ethereum. + +But the tradeoff here is that allowing this on the Bitcoin chain opens up a lot of new attack vectors and undermines a core tenet of Bitcoin: the fact that it is very simple and very good at doing what it does. + +Vitalik originally wanted to add functionality to Bitcoin, and created Ethereum when that didn't work. There's good reason for this. Allowing additional functionality like this exposes Bitcoin to more risk and attack vectors, this conundrum is what Stacks seeks to solve with sBTC. How can we achieve the same functionality as Ethereum but keep the security of Bitcoin? + +One possible route is by separating the programming and money layers, as Stacks and a few other chains do. While Stacks is a good chunk of the way towards this goal right now, due to the [PoX mechanism](../stacks-academy/proof-of-transfer.md), there is still some work to be done before it can be considered a Bitcoin programming layer. + +Specifically, it needs a tighter connection to the Bitcoin chain than PoX currently provides, and needs to share complete finality with Bitcoin. + +Second, it needs a completely trustless, decentralized two-way peg between the Stacks chain and Bitcoin, so that end users only have to send Bitcoin to an address, have things happen on the Stacks side, and have Bitcoin returned to them. + +These issues are currently being addressed with sBTC and the Stacks Nakamoto Release, both of which you can [read about on Stacks' website](https://www.stacks.co/learn/sbtc). + +## Bitcoin-First Applications in the Wild + +Putting all of this information together we can begin to see how we might build applications that are Bitcoin-first. The ultimate goal of Stacks is to serve as an invisible programming layer for Bitcoin, where STX operates primarily as a gas token to operate the Stacks network, but users only ever have to interact with it using their Bitcoin wallet. + +One of the most interesting projects currently taking advantage of this functionality is Zest, which uses a protocol called Magic under the hood to trustlessly swap BTC on the Bitcoin chain for xBTC on the Stacks chain. Zest is a protocol for decentralized borrowing and lending with Bitcoin. + +Here are the basics of how it works: + +1. First, Zest generates a unique [HTLC](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) Bitcoin address for liquidity providers to deposit their BTC to, this uses [Magic Protocol](https://www.magic.fun/) under the hood, which allows users to trustlessly swap BTC for xBTC. + +2. After LP (liquidity provider) sends funds to the HTLC address and the block is confirmed, the payment is considered in escrow. + +3. Now Stacks comes in by reading the Bitcoin state and verifying that deposit actually occurred on the BTC chain, and escrows the corresponding amount of xBTC if it did. If for some reason that were to fail, the LP is still in control of their BTC funds. + +4. Once that escrow is confirmed, LP signs a Stacks transaction that transfers control of the BTC over to Magic, at which point Magic controls the BTC and xBTC is transferred to the Zest liquidity pool. Zest tokens are then minted on the Stacks chain, representing a claim token for the LP's BTC funds + +The cool thing is that this all happens in a single Stacks block, because Stacks and Bitcoin blocks are completed in lockstep. For more details on how Magic handles this process we highly recommend [checking out their docs](https://magicstx.gitbook.io/magic-protocol/guides/technical-overview). + +To dive deeper into the details of how Zest is building a Bitcoin-first application, [check out their docs](https://zestprotocol.gitbook.io/zest/what-is-zest-protocol/the-technology-under-the-hood), and if you are interested in building something like this out for yourself, check out their smart contracts. + +## How to Build Bitcoin-First Dapps with Stacks + +We are currently working on a Stacks Cookbook, which will provide numerous examples for how to build Bitcoin-first apps using both Clarity and frontend Stacks and Bitcoin libraries. + +Until then, you can take a look at Magic and Zest, the protocols mentioned above, to see how they are going about facilitating this process using xBTC and model your applications after them. + +We are in the very early stages of being able to unlock and use BTC in decentralized applications, and much more content and tools will be created in the coming year to make this process easier for developers. + +## What's Next? + +As mentioned earlier on this page, xBTC is not an ideal solution. xBTC is a custodial solution run by [Wrapped](https://wrapped.com/). It does however, give us the building blocks we need to begin building Bitcoin-first applications with Stacks. And updates from Stacks 2.1 make it easier to perform these actions. + +With sBTC on its way, we'll begin to see a new batch of innovative projects that are able to build truly trustless, decentralized dapps with Bitcoin. + +Here are some resources to dive into to learn more about improvements coming to Stacks via the 2.1 upgrade, Nakamoto release, and sBTC. + +- [List of New Clarity Functions for 2.1](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md#clarity) +- [How the Stacks 2.1 Transition Impacts Stacking](https://www.hiro.so/blog/how-the-stacks-2-1-transition-impacts-stacking) +- [Developer's Guide to Stacks 2.1](https://www.hiro.so/blog/a-developers-guide-to-stacks-2-1) +- [Learn About sBTC](https://www.stacks.co/learn/sbtc) +- [Stacks Nakamoto Release](https://stx.is/nakamoto) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/index.md new file mode 100644 index 0000000000..a5bdb3c790 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/index.md @@ -0,0 +1,11 @@ +--- +title: Stacks Academy +description: An introduction to Stacks +sidebar_position: 3 +--- + +# Stacks Academy + +Stacks Academy is designed to give you a start-to-finish introduction to Stacks, what it is, what problems it solves, and how it works. If you are looking to learn how to build on it, the [Tutorials](../tutorials/) are the best place for that. + +Let's get started by diving into exactly what the Stacks blockchain is. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md new file mode 100644 index 0000000000..17a84e4e12 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/microblocks.md @@ -0,0 +1,107 @@ +--- +title: Microblocks +description: Guide to Stacks Microblocks +sidebar_position: 5 +--- + +## Introduction + +Microblocks are a protocol-level feature of the Stacks blockchain that solve the technical challenge of transaction latency. + +Because each Stacks block is anchored to a Bitcoin block through the [Proof-of-Transfer consensus mechanism](../stacks-academy/proof-of-transfer), Stacks is necessarily limited to the same block times as the Bitcoin network. Microblocks allow the Stacks blockchain to perform state transitions between anchor blocks. + +Microblocks are a powerful mechanism for developers to create performant, high quality applications on Stacks, while still inheriting the security of Bitcoin. + +## Transaction states + +The [Stacks block production model](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.) is described in SIP-001. The standard outlines the mechanism by which elected block leaders can produce blocks on the Stacks blockchain either by batching transactions or by streaming them. Microblocks are the product of the streaming model. + +If a block leader has elected to mine microblocks, the leader selects transactions from the mempool and package them into microblocks during the current epoch. Microblocks are blocks of transactions included by a miner after the previous anchor block has been mined, but before the next block is selected. Transactions included in microblocks are processed by the network: their results are known. + +Consider a transaction from the perspective of the number of block confirmations it has. A transaction included in a microblock might have the following example lifecycle: + +``` +Transaction 1 is broadcast to the mempool. It has 0 confirmations. +Transaction 1 is included in a microblock. It still has 0 confirmations, but the results of the transaction are known +Transaction 1 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 1 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 1 has 3 confirmations. +... +``` + +Consider a similar transaction that is not included in a microblock: + +``` +Transaction 2 is broadcast to the mempool. It has 0 confirmations. +Transaction 2 is included in the next anchor block. It has 1 confirmation. +The next Stacks block confirms the previous block. Transaction 2 has 2 confirmations. +The next Stacks block confirms the previous block. Transaction 2 has 3 confirmations. +``` + +The lifecycle of the two transactions is similar, but the difference is pending state. Many Bitcoin wallets display 0-confirmation balances: your wallet balance with any mempool transactions already applied. This is useful because it tells you when you've sent a transaction or received one. With smart contracts, displaying pending state is not as straightforward, because smart contracts do not just transfer inputs to outputs, they may call other contracts, emit events, or perform other computations. A transaction processed in a microblock generates all that information. + +:::tip +If a transaction is dependent on a chain state that could by altered by previous transactions with serious +implications, you should carefully consider whether it should be performed using microblocks. +::: + +## Enabling microblocks + +Miners can choose to enable or disable microblocks in their mining configuration. As a best practice, miners should enable microblock mining. When an application or user submits a transaction, the transaction can include an argument that requires the transaction to be in a microblock, an anchor block, or in either. + +### Transactions + +Transactions include an option that controls if a miner should include them in microblocks or in anchor blocks. The anchor mode transaction option is an optional argument that controls whether a transaction must be included in an anchor block or a microblock, or is eligible for either. + +### Mining + +Stacks miners must enable microblocks in their miner configuration to implement the block streaming model. For more information, see [mining microblocks](../stacks-academy/mining#microblocks). + +## Developing with microblocks + +In most cases, information from transactions included in microblocks should be treated like information from any other block. Wallets and explorers should display the consequences of microblock transactions as the current state of the network. This state should be acknowledged as tentative. + +A microblock transaction can end up being reorganized in the next block rather than just being confirmed as-is. Because of this, your UI should communicate to users if the outputs of a transaction changed, or if the transaction's associated block changed. This is the same outcome as if a 1-block fork occurred. + +### Stacks.js Library + +If you are using Hiro's, Stacks.js, it provides the [AnchorMode](https://stacks.js.org/enums/transactions.AnchorMode.html) argument on transaction objects so that your application can set the microblocks preference for transactions. + +### API + +:::danger API support for microblocks is a work-in-progress. Review the [API documentation][microblocks_api] carefully to ensure that you are up-to-date on the latest implementation details for microblocks. ::: + +The Stacks Blockchain API exposes microblocks through several endpoints. Please review the [Stacks Blockchain API guide](https://docs.hiro.so/get-started/stacks-blockchain-api#microblocks-support) for more details. + +## Best practices + +Working with microblocks is a design decision that you must make for your own application. When working with microblocks, the following best practices are recommended. + +### Handling nonce + +Nonce handling with microblocks is challenging because the next account nonce must take into account any nonce values included in microblocks, which may not yet be included in an anchor block. The Stacks Blockchain API [provides an endpoint][] to retrieve the next nonce for a given principal. + +### Application design + +The state of microblock transactions should be carefully communicated to users. No transaction is final until it's included in an anchor block, and your application design should reflect this. + +The following guidelines are provided as an initial set of best practices for UI design when incorporating microblocks into your application. + +#### Explorers + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. Indicate visually that displayed balances depend on pending state. Indicate visually that displayed balances depend on pending state. + +#### Wallets + +Display pending state, but warn that a transaction is still pending. Indicate visually that displayed balances depend on pending state. + +#### Exchanges + +Continue to count confirmations, microblocks should be considered pending. + +#### Applications + +Microblock communication is highly app-dependent. For some applications, displaying a pending or 0-confirmation transaction as confirmed may be fine. For example, storing data on the chain, or querying the BNS contract. For other applications, such as the transfer of real value, waiting for 3-confirmations would be prudent before displaying the state as confirmed. + +[provides an endpoint]: https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling +[microblocks_api]: https://docs.hiro.so/api#tag/Microblocks diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/mining.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/mining.md new file mode 100644 index 0000000000..9150fcdac1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/mining.md @@ -0,0 +1,84 @@ +--- +title: Mining +description: A guide to mining on Stacks 2.0 +sidebar_position: 4 +--- + +## Introduction + +This guide highlights some technical details related to mining on the Stacks 2.0 network. + +For steps on how to setup your own miner please refer to [miner on testnet](nodes-and-miners/miner-testnet.md) and [miner on mainnet](nodes-and-miners/miner-testnet.md). + +## Mining frequency + +A new Stacks block may be mined once per Bitcoin block. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. To be considered for mining a block, a miner must have a block commit included in a Bitcoin block. If a miner wishes to update their commitment after submission, they may use Bitcoin Replace-By-Fee. + +## Coinbase rewards + +Miners receive coinbase rewards for blocks they win. + +The reward amounts are: + +- 1000 STX per block are released in the first 4 years of mining +- 500 STX per block are released during the following 4 years +- 250 STX per block are released during the following 4 years +- 125 STX per block are released from then on indefinitely. + +These "halvings" are synchronized with Bitcoin halvings. + +![coinbase rewards](/img/pages/coinbase-rewards.png) + +## Transaction fees + +Miners receive Stacks fees for transactions mined in any block they produce. + +For transactions mined in microblocks, the miner that produces the microblock receives 40% of the fees, while the miner that confirms the microblock receives 60% of the fees. + +## Reward maturity + +Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. Block rewards and transaction fees take 100 blocks on the Bitcoin blockchain to mature. After successfully mining a block your rewards appear in your Stacks account after ~24 hours. + +## Mining with proof-of-transfer + +Miners commit Bitcoin to **two** addresses in every leader block commit. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. The amount committed to each address must be the same. The addresses are chosen from the current reward set of stacking participants. Addresses are chosen using a verifiable-random-function, and determining the correct two addresses for a given block requires monitoring the Stacks chain. + +![mining with pox](/img/pages/mining-with-pox.png) + +PoX mining is a modification of Proof-of-Burn (PoB) mining, where instead of sending the committed Bitcoin to a burn address, it's transferred to eligible STX holders that participate in the stacking protocol. + +:::note +A PoX miner can only receive newly minted STX tokens when they transfer Bitcoin to eligible owners of STX tokens +::: + +![Mining flow](/img/pox-mining-flow.png) + +Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: Miners run Stacks nodes with mining enabled to participate in the PoX mechanism. The node implements the PoX mechanism, which ensures proper handling and incentives through four key phases: + +- Registration: miners register for a future election by sending consensus data to the network +- Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders Commitment: registered miners transfer Bitcoin to participate in the election. Committed BTC are sent to a set participating STX token holders Committed BTC are sent to a set participating STX token holders +- Election: a verifiable random function chooses one miner to write a new block on the Stacks blockchain +- Assembly: the elected miner writes the new block and collects rewards in form of new STX tokens + +## Probability to mine next block + +The miner who is selected to mine the next block is chosen depending on the amount of BTC the miners sent, that is, transferred or burnt. + +The probability for a miner to mine the next block equals the BTC the miner sent divided by the total BTC all miners sent. + +While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. While there is no minimum BTC commitment enforced by the protocol, in practice, there's a floor constrained by [dust](https://unchained-capital.com/blog/dust-thermodynamics/)": basically, if the fees for a transaction exceed the value of the spent output, it's considered dust. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. How dust is [calculated](https://github.com/bitcoin/bitcoin/blob/master/src/policy/policy.cpp#L14) depends on a number of factors, we've found 5,500 satoshis to be good lower bound per [output](https://learnmeabitcoin.com/technical/output). Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. Bitcoin transactions from Stacks miners contain two outputs (for Proof-of-Transfer), so a commitment of at least 11,000 satoshis / block is recommended. + +To calculate the amount of BTC to send miners should: + +- Guess the price BTC/STX for the next day (100 blocks later) +- Guess the total amount of BTCs committed by all miners + +## Microblocks + +The Stacks blockchain produces blocks at the same rate as the Bitcoin blockchain. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. In order to provide lower latency transactions, miners can opt to enable microblocks. Microblocks allow the current block leader to stream transactions and include their state transitions in the current epoch. + +If a block leader opts to produce microblocks, the next leader builds the chain tip off the last microblock that the current leader produces. + +The block streaming model is described in [SIP-001][]. + +[SIP-001]: https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md#operation-as-a-leader diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/network.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/network.md new file mode 100644 index 0000000000..7826244499 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/network.md @@ -0,0 +1,152 @@ +--- +title: Network +description: Guide to the Stacks 2.0 network +sidebar_position: 5 +--- + +## Tokens + +Stacks (STX) tokens are the native tokens on the Stacks 2.0 blockchain. The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). The smallest fraction is one micro-STX. 1,000,000 micro-STX make one Stacks (STX). + +STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). For display purposes, micro-STX are divided by 1,000,000 (decimal precision of 6). + +## Fees + +Fees are used to incentivize miners to confirm transactions on the Stacks 2.0 blockchain. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](/understand-stacks/testnet), it is set to 1 micro-STX. The fee is calculated based on the estimate fee rate and the size of the raw transaction in bytes. The fee rate is a market determined variable. For the [testnet](testnet), it is set to 1 micro-STX. + +Fee estimates can obtained through the [`GET /v2/fees/transfer`](https://docs.hiro.so/api#operation/get_fee_transfer) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/fees/transfer' +``` + +The API will respond with the fee rate (as integer): + +```json +1 +``` + +[The Stacks Transactions JS library](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) supports fee estimation for: + +- token transfers (`estimateTransfer`) +- contract deploys (`estimateContractDeploy`) +- non read-only contract calls (`estimateContractFunctionCall`) + +:::tip For an implementation using a different language than JavaScript, please review [this reference implementation](https://github.com/hirosystems/stacks.js/blob/master/packages/transactions/src/builders.ts#L97). ::: ::: ::: + +## Nonces + +Every account carries a [nonce property](https://en.wikipedia.org/wiki/Cryptographic_nonce) that indicates the number of transactions processed for the given account. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. Nonces are one-time codes, starting at `0` for new accounts, and incremented by 1 on every transaction. + +Nonces are added to all transactions and help identify them in order to ensure transactions are processed in order and to avoid duplicated processing. + +:::tip +The consensus mechanism also ensures that transactions aren't "replayed" in two ways. First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: First, nodes query its unspent transaction outputs (UTXOs) in order to satisfy their spending conditions in a new transaction. Second, messages sent between nodes review sequence numbers. +::: + +When a new token transfer transaction is constructed, the most recent nonce of the account needs to fetched and set. + +:::tip The API provides an endpoint to [simplify nonce handling](https://docs.hiro.so/get-started/stacks-blockchain-api#nonce-handling). ::: ::: ::: + +## Confirmations + +The Stacks 2.0 network is anchored onto the bitcoin network. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. This allows transactions on Stacks to inherit the same finality and security of the Bitcoin blockchain. + +The time to mine a block, to confirm transactions, will eventually match the expected "block time" of the bitcoin network: 10 minutes. + +:::tip Transactions can also be mined in [microblocks](microblocks), reducing the latency significantly. ::: ::: ::: + +The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The block time is hardcoded and will change throughout the implementation phases of the [testnet](/understand-stacks/testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: The block time is hardcoded and will change throughout the implementation phases of the [testnet](testnet). The block time is hardcoded and will change throughout the implementation phases of the [testnet](/understand-stacks/testnet). The current block time can be obtained through the [`GET /extended/v1/info/network_block_times`](https://docs.hiro.so/api#operation/get_network_block_times) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/extended/v1/info/network_block_times' +``` + +The API will respond with the block time (in seconds): + +```js +{ + "testnet": { + "target_block_time": 120 + }, + "mainnet": { + "target_block_time": 600 + } +} +``` + +## Read-only function calls + +Smart contracts can expose public function calls. Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. Smart contracts can expose public function calls. For functions that make state modifications to the blockchain, transactions need to be generated and broadcasted. + +However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). However, for read-only function calls, transactions are **not** required. Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). Instead, these calls can be done using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +:::tip +Read-only function calls do not require transaction fees +::: + +A read-only contract call can be done using the [`POST /v2/contracts/call-read///`](https://docs.hiro.so/api#operation/call_read_only_function) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl --location --request POST 'https://stacks-node-api.testnet.stacks.co/v2/contracts/call-read///' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "sender": ".", + "arguments": [, ...] +}' +}' +}' +}' +``` + +Sample response for a successful call: + +```js +{ + "okay": true, + "result": "" +} +``` + +:::tip To set the function call arguments and read the result, Clarity values need to be serialized into a hexadecimal string. The [Stacks Transactions JS](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions) library supports these operations ::: + +## Querying + +Stacks 2.0 network details can be queried using the [Stacks Blockchain API](https://docs.hiro.so/get-started/stacks-blockchain-api). + +### Health check + +The [status checker](https://stacks-status.com/) is a service that provides a user interface to quickly review the health of the Stacks 2.0 blockchain. + +### Network info + +The network information can be obtained using the [`GET /v2/info`](https://docs.hiro.so/api#operation/get_core_api_info) endpoint: + +```bash +# for mainnet, replace `testnet` with `mainnet` +curl 'https://stacks-node-api.testnet.stacks.co/v2/info' +``` + +Sample response: + +```js +{ + "peer_version": 385875968, + "burn_consensus": "826401d65cf3671210a3fb135d827d549c0b4d37", + "burn_block_height": 1972, + "stable_burn_consensus": "e27ea23f199076bc41a729d76a813e125b725f64", + "stable_burn_block_height": 1971, + "server_version": "blockstack-core 0.0.1 => 23.0.0.0 (master:bdd042242+, release build, linux [x86_64]", + "network_id": 2147483648, + "parent_network_id": 3669344250, + "stacks_tip_height": 933, + "stacks_tip": "1f601823fbcc5b6b2215b2ff59d2818fba61ee4a3cea426d8bc3dbb268005d8f", + "stacks_tip_burn_block": "54c56a9685545c45accf42b5dcb2787c97eda8185a1c794daf9b5a59d4807abc", + "unanchored_tip": "71948ee211dac3b241eb65d881637f649d0d49ac08ee4a41c29217d3026d7aae", + "exit_at_block_height": 28160 +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md new file mode 100644 index 0000000000..bb0727194f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/post-conditions.md @@ -0,0 +1,39 @@ +--- +title: Post Conditions +description: What post conditions are and how they work +sidebar_position: 10 +--- + +Post conditions are one of the most interesting and unique aspects of Stacks. + +From the beginning, safety and security has been at the heart of the Stacks ethos and formed the foundation of architecture decisions when building it. + +Like Clarity, Stacks' smart contract programming language, post conditions were specifically built and design to solve the problem of user safety when interacting with blockchain applications. + +So what are they and how do they work? + +## How Post Conditions Work + +Post conditions are conditions that are set on the client side to ensure that a smart contract does not perform any unexpected behavior. + +Let's look at an example to make this more concrete. + +Let's say a user is on an NFT marketplace and is expecting to purchase an NFT for 100 STX. Using post conditions, the developer who is building the frontend of the application can add in post conditions to ensure that this is in fact what happens when the user initiates the transaction. + +If it does not, the transaction will abort and the user won't be out anything except the transaction fee. + +It's important to note that post conditions do not live in smart contracts. They are designed to be an extra layer of security on top of smart contracts. + +The problem they help address is a user interacting with a malicious smart contract that attempts to do something the user does not expect. + +But rather than simply being a UI feature of a wallet, these post conditions are built into the Stacks blockchain itself and are enforced at the protocol level. + +When you use a Stacks wallet like the Hiro web wallet and initiate a transaction, the wallet will display the post conditions set by the developer and tell the user exactly what is going to happen. If the action taken by the smart contract matches, the transaction goes through fine, otherwise it aborts. + +Here's what that looks like: + +![Stacks post condition example](./post-condition.jpeg) + +In this example, if the smart contract does not transfer one fabulous-frog NFT and and take 50 STX from the user, the transaction will abort. + +You can learn more about how post conditions work in [SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) and how to utilize them in your applications in the tutorial, [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65). diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md new file mode 100644 index 0000000000..5697840907 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/proof-of-transfer.md @@ -0,0 +1,83 @@ +--- +title: Proof of Transfer +description: Understand the proof-of-transfer consensus mechanism +sidebar_position: 3 +--- + +In the previous section, we took a look at the vision and ethos of Stacks. We talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. + +In this section, we'll run through the consensus mechanism that makes that happen, Proof of Transfer. + +Consensus algorithms for blockchains require compute or financial resources to secure the blockchain. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. The general practice of decentralized consensus is to make it practically infeasible for any single malicious actor to have enough computing power or ownership stake to attack the network. + +Popular consensus mechanisms in modern blockchains include proof of work, in which nodes dedicate computing resources, and proof of stake, in which nodes dedicate financial resources to secure the network. + +Proof of burn is another, less-frequently used consensus mechanism where miners compete by ‘burning’ (destroying) a proof of work cryptocurrency as a proxy for computing resources. + +Proof of transfer (PoX) is an extension of the proof of burn mechanism. PoX uses the proof of work cryptocurrency of an established blockchain to secure a new blockchain. However, unlike proof of burn, rather than burning the cryptocurrency, miners transfer the committed cryptocurrency to some other participants in the network. + +![PoX mechanism](/img/pox-mechanism.png) + +This allows network participants to secure the PoX cryptocurrency network and earn a reward in the base cryptocurrency. Thus, proof-of-transfer blockchains are anchored on their chosen proof-of-work chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. Thus, PoX blockchains are anchored on their chosen PoW chain. Stacks uses [Bitcoin](#why-bitcoin) as its anchor chain. + +![PoX participants](/img/pox-participants.png) + +## Why Bitcoin? + +There are a number of reasons that Stacks chose Bitcoin as the blockchain to power consensus. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. It's the oldest blockchain protocol, having launched in 2009, and has become a recognized asset outside of the cryptocurrency community. BTC has held the highest market capitalization of any cryptocurrency for the past decade. + +Bitcoin champions simplicity and stability, and has stood the test of time. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the proof-of-transfer consensus mechanism. Influencing or attacking the network is infeasible or impractical for any potential hackers. It's one of the only cryptocurrencies to capture public attention. Bitcoin is a household name, and is recognized as an asset by governments, large corporations, and legacy banking institutions. Lastly, Bitcoin is largely considered a reliable store of value, and provides extensive infrastructure to support the PoX consensus mechanism. + +SIP-001 provides a full [list of reasons why Bitcoin was chosen to secure Stacks](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). + +:::note +By the way, SIP stands for Stacks Improvement Proposal, and it's the process by which community members agree on making changes to the network, we'll look at these in a future lesson. +::: + +## Blocks and microblocks + +The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. The Stacks blockchain allows for increased transaction throughput using a mechanism called microblocks. Bitcoin and Stacks progress in lockstep, and their blocks are confirmed simultaneously. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. On Stacks, this is referred to as an ‘anchor block’. An entire block of Stacks transactions corresponds to a single Bitcoin transaction. This significantly improves cost/byte ratio for processing Stacks transactions. Because of simultaneous block production, Bitcoin acts as a rate-limiter for creating Stacks blocks, thereby preventing denial-of-service attacks on its peer network. + +However, in between Stacks anchor blocks settling on the Bitcoin blockchain, there are also a varying number of microblocks that allow rapid settlement of Stacks transactions with a high degree of confidence. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. This allows Stacks transaction throughput to scale independently of Bitcoin, while still periodically establishing finality with the Bitcoin chain. The Stacks blockchain adopts a block streaming model whereby each leader can adaptively select and package transactions into their block as they arrive in the mempool. Therefore when an anchor block is confirmed, all of the transactions in the parent microblock stream are packaged and processed. This is an unprecedented method for achieving scalability without creating a totally separate protocol from Bitcoin. + +![stx-microblock](/img/stx-microblocks.png) + +## Unlocking Bitcoin capital + +In the previous section we talked about Stacks being able to allow us to build a decentralized economy on top of Bitcoin and that PoX was a key piece of being able to do that. + +The reason is two-fold. First, as a part of this PoX mining process we have covered here, a hash of each Stacks block is recorded to the OP_RETURN opcode of a Bitcoin transaction. If you aren't familiar, the OP_RETURN opcode allows us to store up to 40 bytes of arbitrary data in a Bitcoin transaction. + +:::note +This [Stack Exchange answer](https://bitcoin.stackexchange.com/questions/29554/explanation-of-what-an-op-return-transaction-looks-like) gives a good overview of the reasoning and history of this opcode. +::: + +This is how Stacks records its history to the Bitcoin chain and why it inherits some security as a result of this process. If you wanted to try and create a false Stacks fork, you would have to broadcast the entire process to the Bitcoin chain. + +Similarly, if you wanted to try and change the history of the Stacks chain, you would have to somehow modify these OP_RETURN values in each corresponding Bitcoin block, meaning you would have to compromise Bitcoin in order to compromise the history of Stacks. + +:::caution +Note that this is not the same thing as saying that you need to compromise Bitcoin in order compromise Stacks at all, but simply that in order to falsify the history of the Stacks chain you would have to also falsify the history of the Bitcoin chain. +::: + +Additionally, part of this PoX process involves each Stacks block also knowing which Bitcoin block it is anchored to. Clarity, Stacks' smart contract language, has built-in functions for reading this data, such as [`get-block-info`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#get-block-info), which returns, among other things, a field called `burnchain-header-hash`, which gives us the hash of the Bitcoin header corresponding to this Stacks block. + +This allows us to do really interesting things like trigger certain things to happen in a Clarity contract by watching the chain and verifying whether or not certain transactions occurred. You can see this in action in [Catamaran Swaps](https://docs.catamaranswaps.org/en/latest/catamaran.html), with other interesting projects like [Zest](https://www.zestprotocol.com/) seeking to expand on this functionality. + +The ultimate goal of all this is to enable the vision of web3, building a decentralized economy and enabling true user ownership of assets and data, on top of Bitcoin as a settlement layer, and using Bitcoin as a base decentralized money. + +![Unlocking Bitcoin](/img/pox-unlocking-btc.png) + +We also recommend [reading the full PoX whitepaper](https://community.stacks.org/pox), as it breaks down the reasoning behind creating a PoX chain and the unique benefits we get from doing so. + +## Proof of Transfer Contracts and Technical Details + +The Proof of Transfer functionality is implemented on the Stacks chain via a [Clarity smart contract](https://explorer.stacks.co/txid/0xfc878ab9c29f3d822a96ee73898000579bdf69619a174e748672eabfc7cfc589). An overview of this contract is [available in the docs](../clarity/noteworthy-contracts/stacking-contract.md). + +You can see the original design for stacking and proof of transfer by reading the relevant SIP, [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md). You can also utilize [Hiro's API](https://docs.hiro.so/api#tag/Info/operation/get_pox_info) to get proof of transfer details including the relevant contract address. + +However, since Stacks mainnet launched in January 2021, several shortcomings have been recognized in the stacking process, which are being corrected in the next major network epoch, Stacks 2.1 You can read more about these changes in [SIP-015](https://github.com/stacksgov/sips/blob/feat/sip-015/sips/sip-015/sip-015-network-upgrade.md), the SIP responsible for managing the upgrade to 2.1. + +### Got another question + +Have another question not answered here? Post in on Stack Overflow under the appropriate tag(s) and post the link to the Stack Overflow question in the Stacks Discord in the appropriate channel. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/sips.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/sips.md new file mode 100644 index 0000000000..592021dc6b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/sips.md @@ -0,0 +1,55 @@ +--- +title: SIPs +description: SIPs +sidebar_position: 2 +--- + +## Stacks Improvement Proposals (SIPs) + +Stacks improvement proposals (SIPs) are aimed at describing the implementation of the Stacks blockchain, as well as proposing improvements. + +The SIP process [(SIP-000)](https://github.com/stacksgov/sips/blob/main/sips/sip-000/sip-000-stacks-improvement-proposal-process.md) describes how to make a SIP and get it ratified. + +They should contain concise technical specifications of features or standards and the rationale behind it. SIPs are intended to be the primary medium for proposing new features, for collecting community input on a system-wide issue, and for documenting design decisions. + +The SIPs are located in the [stacksgov/sips](https://github.com/stacksgov/sips) repository as part of the [Stacks Community Governance organization](https://github.com/stacksgov). + +Anyone in the Stacks community can submit a SIP. + +:::tip Stacks Improvement Proposals Community Calls +Add the [weekly community SIP call](https://www.addevent.com/event/wS15955379) to your calendar. + +SIP Meeting calls are recorded and available [here](https://www.youtube.com/playlist?list=PLg717Ri_rTnx5kuaWqp3cUAtwQk_yzslT) + +More details of the meetings are available [here](https://github.com/stacksgov/sips/issues/79) +::: + +## Ratified SIPSs + +- [x] [SIP 001: Burn Election](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) +- [x] [SIP 002: Clarity, a language for predictable smart contracts](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md) +- [x] [SIP 003: Peer Network](https://github.com/stacksgov/sips/blob/main/sips/sip-003/sip-003-peer-network.md) +- [x] [SIP 004: Cryptographic Commitment to Materialized Views](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md) +- [x] [SIP 005: Blocks, Transactions, and Accounts](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md) +- [x] [SIP 006: Clarity Execution Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-006/sip-006-runtime-cost-assessment.md) +- [x] [SIP 007: Stacking Consensus](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- [x] [SIP 008: Clarity Parsing and Analysis Cost Assessment](https://github.com/stacksgov/sips/blob/main/sips/sip-008/sip-008-analysis-cost-assessment.md) +- [x] [SIP 009: Standard Trait Definition for Non-Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) +- [x] [SIP 010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) +- [x] [SIP 012: Burn Height Selection for a Network Upgrade to Introduce New Cost-Limits](https://github.com/stacksgov/sips/blob/main/sips/sip-012/sip-012-cost-limits-network-upgrade.md) +- [x] [SIP-015: Stacks Upgrade of Proof-of-Transfer and Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) +- [x] [SIP-016: Metadata for Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-016/sip-016-token-metadata.md) +- [x] [SIP-018: Signed Structured Data](https://github.com/stacksgov/sips/blob/main/sips/sip-018/sip-018-signed-structured-data.md) +- [x] [SIP-020: Bitwise Operations in Clarity](https://github.com/stacksgov/sips/blob/main/sips/sip-020/sip-020-bitwise-ops.md) + +## How to Get Involved + +There are several ways you can get involved with the SIP process: + +- **Join the weekly SIP Meeting call** listed [here](https://community.stacks.org/events). + +- **SIP Editor**. SIP editors help SIP authors make sure their SIPs are well-formed and follow the right process. They help get SIPs ready for deep review by advancing it them from Draft to Accepted status. If you want to become a SIP editor, open an issue with your name and email to ask to be added to the list of SIP editors. + +- **Join a CAB** (Consideration Advisory Board). SIPs fall under the purview of one or more considerations. A full list is in [this github](https://github.com/stacksgov/sips/tree/main/considerations) directory. Currently they are: Diversity, Economics, Ethics, Governance and Technical. Members of SIP consideration advisory boards use their domain expertise to give Accepted SIPs a deep read, and give the authors any/all feedback to help make the SIP workable. If you want to join a board, reach out to the board's chairperson via the listed contact information. + +- **Steering Committee**. The Steering Committee organizes the consideration advisory boards and votes to advance Recommended SIPs to Activation-in-Progress status, and then to either Ratified or Rejected status. Once they are in the process of being activated, they use a SIP's Activation section to determine whether or not the Stacks ecosystem has ratified or rejected the SIP. Joining this committee requires the consent of the Stacks Foundation board. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md new file mode 100644 index 0000000000..9ed9c667fc --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/stacking.md @@ -0,0 +1,183 @@ +--- +title: Stacking +description: Introduction to the reward mechanism of Proof-of-Transfer +sidebar_position: 11 +--- + +## Introduction + +Stacking rewards Stacks (STX) token holders with bitcoin for providing a valuable service to the network by locking up their tokens for a certain time. + +## Stacking vs Staking + +It is crucial to note that this has no impact on block production or validation. **Stacks is not a Proof-of-Stake network and _stacking_ is different than _staking_**. + +There are two primary differences between stacking in Stacks and staking in other PoS networks. + +### Yield generated in burnchain token + +In staking, users lock one token and earn their yield in the same token. In stacking, users lock one token (STX) and earn a yield in the "burnchain" token (BTC), rather than the same token that was locked. In [PoX](./proof-of-transfer.md), the yield comes from a finite, external source (Bitcoin deposits from Stacks miners). In PoS, the yield comes from the currency's issuance schedule itself, which means it is programmatically unlimited (but theoretically limited, we'll get into this a bit more below). + +That's the first main difference. Staking involves a yield of the same token being generated by the issuance mechanism set by the core protocol, where stacking yield requires an input of an external, separate token. + +How are these issuance rates set? In Ethereum, issuance rates are determined by network usage. Ethereum's goal is to create a deflationary money supply, so the issuance rate is determined depending on the usage of the network. In order for an Ethereum transaction to be considered valid, it must include a base fee that is burned during transaction execution. The [issuance rate is algorithmically determined](https://ethereum.org/en/roadmap/merge/issuance/#post-merge) block-by-block depending on how much ETH is being burned by these base fees plus normal gas fees. + +Stacking doesn't have any of this complex functionality, since it does not generate a yield of the same token (and therefore doesn't need to issue new tokens, but rather transfer existing tokens from the base network) and it does not need to maintain an issuance rate. We are speaking here of the yield specifically, Stacks does have an issuance rate and does generate new STX tokens, but this process is completely separate from stacking and the yield generated from it. + +The Bitcoin yield that stackers earn is determined by a combination of the Bitcoin being committed by miners and the number of STX tokens that are locked up in the network. + +### No effect on transaction validation or consensus mechanism + +The other main difference is that staking involves validators, and is tightly coupled with the operations of the network. + +In both protocols stackers/stakers are earning a yield for providing a service. In PoX, that service is providing economic security by signaling what the canonical Stacks chain is (the chain with the most money locked in it is the real chain) and soon will provide the service of serving as signers for [sBTC](https://stacks.co/sbtc). + +In PoS, the service stakers provide is running a validator node, which is in charge of determining what transactions are or are not valid. So in a PoX system with stacking, the yield generation process is not attached to the validity and operations of the network, whereas in PoS it is. + +In PoS, the entities that are locking up their tokens and earning a yield are the same entities that are in charge of determining what does and does not count as a valid transaction. This and the fact that the yield is in the same token that is locked, have large implications on a PoS chain functioning much like equities in that the entities with the largest stake have the most controlling power over the transactional operations of the chain. + +Here's an [article](https://krgrs.dev/why-bitcoin-is-the-biggest-opportunity-for-developers-in-2023#heading-technology-and-economic-incentives) by Stacks Foundation Developer Advocate Kenny Rogers that goes more in-depth into these economic incentives, with additional resources. + +It is important to note that this control does not extend to being able to change the rules of the blockchain itself, but only to vote transactions as valid or invalid. + +In order to incentivize honest behavior on the part of validators, stake can be slashed as a punishment. Since PoX stackers do not have any say in transaction validity, this punishment mechanism does not exist and is not necessary in PoX. + +![](/img/stacking.png) + +Stacking is a built-in action, required by the "proof-of-transfer" (PoX) mechanism. The PoX mechanism is executed by every miner on the Stacks network. + +:::info Stacking functionality is implemented as a smart contract, using [Clarity](../clarity/). [Read more about the contract](../clarity/noteworthy-contracts/stacking-contract). ::: + +## Stacking flow + +The Stacking mechanism can be presented as a flow of actions: + +![Stacking flow](/img/stacking-illustration.png) + +1. Make API calls to get details about the upcoming reward cycle +2. For a specific Stacks account, confirm eligibility +3. Confirm the BTC reward address and the lockup duration +4. The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase The transaction is broadcasted and the STX tokens are locked. This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase This needs to happen before the prepare phase of the next reward cycle, the last 100 Bitcoin blocks of the ongoing reward phase +5. The Stacking mechanism executes reward cycles and sends out rewards to the set BTC reward address +6. During the lockup period, details about unlocking timing, rewards and more can be obtained +7. Once the lockup period is passed, the tokens are released and accessible again +8. Display reward history, including details like earnings for previous reward cycles + +:::info Keep in mind that the target duration for a reward cycles is ~2 weeks. -> Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: -> Keep in mind that the target duration for a reward cycles is ~2 weeks. This duration is based on the target block time of the network (10 minutes) and can be higher at times due to [confirmation time variances](https://www.blockchain.com/charts/median-confirmation-time) of the bitcoin network. ::: + +## Stacking delegation flow + +The Stacking flow is different for delegation use cases: + +![Delegated tacking flow](/img/stacking-delegation-illustration.png) + +- Before Stacking can be initiated for a token holder, the delegator needs to be granted permission to Stack on behalf of the account owner. The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator The permission is restricted to the maximum amount the delegator is allowed to Stack. The maximum amount is not limited by the available funds and can be set much higher. An account can only be associated with one single delegator +- The account has to define the delegation relationship. The account has to define the delegation relationship. The account has to define the delegation relationship. The account has to define the delegation relationship. They can optionally restrict the Bitcoin reward address that must be used for payouts, and the expiration burn block height for the permission, thus limiting the time a delegator has permission to Stack +- Delegators have to lock Stacks from different accounts ("pooling phase") until they reach the minimum amount of Stacks required to participate in Stacking +- Once a delegator locks enough STX tokens, they can finalize and commit their participation in the next reward cycle +- Certain delegation relationships may allow the STX holder to receive the payout directly from the miner (step 5/6) +- The termination of the delegation relationship can either happen automatically based on set expiration rules or by actively revoking delegation rights + +## Token holder eligibility + +Stacks (STX) token holders don't automatically receive stacking rewards. Instead, they must: Instead, they must: Instead, they must: Instead, they must: + +- Commit to participation before a reward cycle begins +- Commit the minimum amount of STX tokens to secure a reward slot, or pool with others to reach the minimum +- Lock up STX tokens for a specified period +- Provide a supported Bitcoin address to receive rewards (p2pkh, p2sh, SegWit, or Taproot) + +The following diagram describes how the minimum STX tokens per slot is determined. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. More information on [dynamic minimums for stacking](https://stacking.club) is available at stacking.club. + +![Dynamic minimum for individual eligibility](/img/stacking-dynamic-minimum.png) + +Token holders have a variety of providers and tools to support their participation in Stacking. Token holders have a variety of providers and tools to support their participation in Stacking. Token holders have a variety of providers and tools to support their participation in Stacking. The Stacks website contains a [list of stacking providers and pools](https://stacks.org/stacking#earn). + +## Stacking in the PoX consensus algorithm + +Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. Stacking is a built-in capability of PoX and occurs through a set of actions on the Stacks blockchain. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. The [full proof-of-transfer implementation details](https://github.com/stacks-network/stacks-blockchain/blob/develop/sip/sip-007-stacking-consensus.md) are in SIP-007. Below is a summary of the most relevant actions of the algorithm. Below is a summary of the most relevant actions of the algorithm. Below is a summary of the most relevant actions of the algorithm. + +![PoX cycles](/img/pox-cycles.png) + +- Stacking happens over reward cycles with a fixed length. Stacking happens over reward cycles with a fixed length. Stacking happens over reward cycles with a fixed length. Stacking happens over reward cycles with a fixed length. In each reward cycle, a set of Bitcoin addresses associated with stacking participants receive BTC rewards +- A reward cycle consists of two phases: prepare and reward +- During the prepare phase, miners decide on an anchor block and a reward set. During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle During the prepare phase, miners decide on an anchor block and a reward set. Mining any descendant forks of the anchor block requires transferring mining funds to the appropriate reward addresses. The reward set is the set of Bitcoin addresses which are eligible to receive funds in the reward cycle +- Miners register as leader candidates for a future election by sending a key transaction that burns cryptocurrency. The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set The transaction also registers the leader's preferred chain tip (must be a descendant of the anchor block) and commitment of funds to 2 addresses from the reward set +- Token holders register for the next rewards cycle by broadcasting a signed message that locks up associated STX tokens for a protocol-specified lockup period, specifies a Bitcoin address to receive the funds, and votes on a Stacks chain tip +- Multiple leaders can commit to the same chain tip. Multiple leaders can commit to the same chain tip. Multiple leaders can commit to the same chain tip. Multiple leaders can commit to the same chain tip. The leader that wins the election and the peers who also burn for that leader collectively share the reward, proportional to how much each one burned +- Token holders' locked up tokens automatically unlock as soon as the lockup period finishes + +## Bitcoin address + +:::note +Currently, all 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot. +::: + +The Stacking contract needs a special format for the Bitcoin address (the reward address). This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. This is required to ensure that miners are able to correctly construct the Bitcoin transaction containing the reward address. + +The address must be specified in the following format using the Clarity language: + +```clar +;; a tuple of a version and hashbytes buffer +(pox-addr (tuple (version (buff 1)) (hashbytes (buff 20)))) +``` + +The `version` buffer must represent what kind of bitcoin address is being submitted. It can be one of the following: It can be one of the following: It can be one of the following: It can be one of the following: + +```js +SerializeP2PKH = 0x00, // hash160(public-key), same as bitcoin's p2pkh +SerializeP2SH = 0x01, // hash160(multisig-redeem-script), same as bitcoin's multisig p2sh +SerializeP2WPKH = 0x02, // hash160(segwit-program-00(p2pkh)), same as bitcoin's p2sh-p2wpkh +SerializeP2WSH = 0x03, // hash160(segwit-program-00(public-keys)), same as bitcoin's p2sh-p2wsh +``` + +The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): The `hashbytes` are the 20 hash bytes of the bitcoin address. You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): You can obtain that from a bitcoin library, for instance using [`bitcoinjs-lib`](https://github.com/bitcoinjs/bitcoinjs-lib): + +```js +const btc = require("bitcoinjs-lib"); +console.log( + "0x" + + btc.address + .fromBase58Check("1C56LYirKa3PFXFsvhSESgDy2acEHVAEt6") + .hash.toString("hex") +); +``` + +## Choosing the right Stacking strategy + +[Here](https://blog.stacks.co/stacking-strategy) is an interesting article that may help you choose the right Stacking strategy. + +## Where to Stack? + +You can Stack on your own, on a pool or on an exchange: + +### Stacking on your own + +Stacking on your own is non-custodial. + +Stacking on your own requires a protocol minimum (amount changes but about 100,000 STX). + +[Hiro Wallet](https://www.hiro.so/wallet) allows stacking on your own. + +### Stacking on a pool + +Stacking on a pool allows Stacking without the requirement of the protocol minimum. + +Some available pools are: + +| Pool | Type | Pays rewards in | Fee | Minimum amount | +| --------------------------------------------------- | ------------- |:---------------:| --- |:--------------:| +| [Friedger's Pool](https://pool.friedger.de/) | Non custodial | STX or xBTC | No | 40 STX | +| [Planbetter](https://planbetter.org/) | Non custodial | BTC | 5% | 200 STX | +| [Stacked](https://staking.staked.us/stacks-staking) | Non custodial | BTC | | 100,000 STX | +| [Xverse](https://www.xverse.app/) | Non custodial | BTC | No | 100 STX | + +### Stacking on an exchange + +Stacking on an exchange is custodial, meaning you are trusting the exchange with your Stacks. + +Several exchanges allow Stacking directly on their sites. Several exchanges allow Stacking directly on their sites. Examples are [Okcoin](https://www.okcoin.com) and [Binance](https://www.binance.com/en/staking) + +## Stacking statistics + +You can view all sorts of Stacking data and statistics on [Stacking Club](https://stacking.club) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md new file mode 100644 index 0000000000..e8418e1b03 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/stacks-blockchain-api.md @@ -0,0 +1,41 @@ +--- +title: Stacks Blockchain API +description: Interacting with the Stacks 2.0 Blockchain via API +sidebar_position: 6 +--- + +## Introduction +The Stacks 2.0 Blockchain API allows you to query the Stacks 2.0 blockchain and interact with smart contracts. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. It was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. + +:::tip API Documentation Official API Documentation is available [here](https://stacks-network.github.io/stacks-blockchain/). ::: + +Note that the [Stacks Node RPC API](https://github.com/stacks-network/stacks-blockchain/) and the [Hiro Stacks API](https://www.hiro.so/stacks-api) are two different things. The Hiro API is a centralized service run by Hiro, a developer tooling company, that makes it easy to get onboarded and begin interacting with the Stacks blockchain in a RESTful way. You can also [run your own API server](https://docs.hiro.so/get-started/running-api-node) + +The Hiro Stacks API is a proxy for the Stacks Node API that makes it a bit easier to work with by providing additional functionality. + +The RPC API is generated by every Stacks node and allows developers to [self-host their own node and API](../nodes-and-miners/) for a more decentralized architecture. + +:::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: :::note This documentation only covers endpoints that are exposed on a Stacks node, referred to as the RPC API. For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: For full documentation on the RESTful API, check out the [Hiro's API reference](https://docs.hiro.so/api). ::: ::: + +The RPC API can be used without any authorization. The basepath for the API is: + +```bash +# for mainnet, replace `testnet` with `mainnet` +https://stacks-node-api.testnet.stacks.co/ +``` + +## Proxied Stacks Node RPC API endpoints +The Stacks 2.0 Blockchain API (Hiro's API) is centrally hosted. The Stacks 2.0 Blockchain API is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. The Stacks 2.0 Blockchain API is centrally hosted. The Stacks 2.0 Blockchain API is centrally hosted. However, every running Stacks node exposes an RPC API, which allows you to interact with the underlying blockchain. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. Instead of using a centrally hosted API, you can directly access the RPC API of a locally hosted Node. + +While the Node RPC API doesn't give the same functionality as the hosted Stacks 2.0 Blockchain API, you get similar functionality in a way that is scoped to that specific node. The RPC API includes the following endpoints: The RPC API includes the following endpoints: The RPC API includes the following endpoints: The RPC API includes the following endpoints: + +- [POST /v2/transactions](https://docs.hiro.so/api#operation/post_core_node_transactions) +- [GET /v2/contracts/interface/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_interface) +- [POST /v2/map_entry/{contract_address}/{contract_name}/{map_name}](https://docs.hiro.so/api#operation/get_contract_data_map_entry) +- [GET /v2/contracts/source/{contract_address}/{contract_name}](https://docs.hiro.so/api#operation/get_contract_source) +- [GET /v2/accounts/{principal}](https://docs.hiro.so/api#operation/get_account_info) +- [POST /v2/contracts/call-read/{contract_address}/{contract_name}/{function_name}](https://docs.hiro.so/api#operation/call_read_only_function) +- [GET /v2/fees/transfer](https://docs.hiro.so/api#operation/get_fee_transfer) +- [GET /v2/info](https://docs.hiro.so/api#operation/get_core_api_info) + +:::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: :::caution If you run a local node, it exposes an HTTP server on port `20443`. The info endpoint would be `localhost:20443/v2/info`. ::: The info endpoint would be `localhost:20443/v2/info`. ::: ::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md new file mode 100644 index 0000000000..2f0acfd26c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/technical-specs.md @@ -0,0 +1,79 @@ +--- +title: Technical Specifications +description: Summary of technical specifications of Stacks 2.0 +sidebar_position: 13 +--- + +## Consensus + +- Proof of Transfer (PoX) as described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) +- Network will transition to Proof of Burn (PoB) as described in [SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) after 10 years. [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). [Learn more about Proof-of-Burn in SIP-001](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md). +- Threat model + - 51% of malicious Stacks mining power can perform a double-spend attack + - 51% of malicious Bitcoin mining power can reorg the Stacks chain +- Different actors and their roles + - Stacks Miners package transactions into blocks, mine them through a Bitcoin transaction, propagate them, and if they win the block race, append microblocks to their winning block until the next block is mined. The next block confirms the microblock stream. The next block confirms the microblock stream. The next block confirms the microblock stream. The next block confirms the microblock stream. + - Stacks Holders may alter the calculation of block limits (subject to a miner veto) and may vote to disable Proof-of-Transfer rewards for a reward cycle. +- Transactions are considered final when the corresponding "block commit" transaction on Bitcoin is finalized. Typically this can by 3-6 confirmations. Typically this can by 3-6 confirmations. Typically this can by 3-6 confirmations. Typically this can by 3-6 confirmations. +- For more details, see [Proof of Transfer](proof-of-transfer). + +## Proof of Transfer Mining + +- Coinbase reward schedule: + - 1000 STX/block for first 4 years + - 500 STX/block for following 4 years + - 250 STX/block for subsequent 4 years + - 125 STX/block in perpetuity after that +- Coinbase rewards accumulate for "missed sortitions": If a Bitcoin block has no sortition (at height N), then any Stacks block mined in a subsequent sortition that builds off of any Stacks chain tip that existed at the penultimate sortition (at height N-1) may claim its coinbase. This encourages miners to keep mining even if Bitcoin fees are high. This encourages miners to keep mining even if Bitcoin fees are high. This encourages miners to keep mining even if Bitcoin fees are high. This encourages miners to keep mining even if Bitcoin fees are high. +- Initial mining bonus: This is a special case of the above to incentivize early miners. Initial mining bonus: This is a special case of the above to incentivize early miners. Coinbase for all burnchain blocks between the first burn block height (to be chosen by independent miners as part of the Stacks 2.0 launch) and the first sortition winner accumulate and are distributed to miners over a fixed window (to be determined). For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. For instance, say burn block height is 10,000 and first sortition is at block 10500 and distribution window is 100 blocks, then coinbase for the first 500 blocks (10,500 - 10,000) will be distributed evenly to miners who win sortition over the subsequent 100 blocks. +- Reward maturity window: 100 blocks, meaning leaders will earn the coinbase reward 100 blocks after the block they successfully mine. +- Block interval: Stacks blockchain produces blocks at the same rate as the underlying burnchain. For Bitcoin, this is approximately every 10 minutes. For Bitcoin, this is approximately every 10 minutes. For Bitcoin, this is approximately every 10 minutes. For Bitcoin, this is approximately every 10 minutes. +- BTC commitment: Miners must commit at least 11,000 satoshis (5,500 sats / [UTXO output](https://learnmeabitcoin.com/technical/utxo)); 2 outputs / block) to avoid "dust." +- For more details, see [Mining](mining). + +## Stacking + +- Stacking works in 2 phases + 1. Prepare phase: In this phase an "anchor block" is chosen. The qualifying set of addresses ("reward set") is determined based on the snapshot of the chain at the anchor block. Length of prepare phase is 100 blocks. Stacking commitments need to be confirmed before this phase starts + 2. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). Reward phase: In this phase miner BTC commitments are distributed amongst the reward set. Reward cycle length is 2000 BTC blocks (~2 weeks). +- Two reward addresses / block, for a total of 4000 addresses every reward cycle. Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. Two reward addresses / block, for a total of 4000 addresses every reward cycle. The addresses are chosen using a VRF (verifiable random function), so each node can deterministically arrive at the same reward addresses for a given block. +- Stacking threshold: 0.025% of the participating amount of STX when participation is between 25% and 100% and when participation is below 25%, the threshold level is always 0.00625 of the liquid supply of STX. +- Delegation: An STX address can designate another address to participate in Stacking on its behalf. [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). [Relevant section in SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation). +- Pooling: STX holders that individually do not meet the Stacking threshold can pool together their holdings to participate in Stacking. To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). To do this, STX holders must set the (optional) reward address to the "delegate address." For more details, see [this reference](https://docs.stacks.co/references/stacking-contract#delegate-stx). +- All 4 address types are supported: Legacy, SegWit, Native SegWit, and Taproot +- Further reading: [Stacking](stacking) + +## Accounts and Addresses + +- Transactions in the Stacks blockchain originate from, are paid for by, and execute under the authority of accounts +- An account is fully specified by its address + nonce + assets +- Address contains 2 or 3 fields: 1 byte version, 20 byte public key hash (RIPEMD160(SHA256(input))), optional name (variable length, max 128 bytes) +- Two types of accounts: standard accounts are owned by one or more private keys; contract accounts are materialized when a smart-contract is instantiated (specified by the optional name field above) +- Nonce counts number of times an account has authorized a transaction. Nonce counts number of times an account has authorized a transaction. Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. Nonce counts number of times an account has authorized a transaction. Nonce counts number of times an account has authorized a transaction. Starts at 0, valid authorization must include the _next_ nonce value. +- Assets are a map of all asset types -- STX, any on-chain assets specified by a Clarity contract (for example NFTs) -- to quantities owned by that account. +- Accounts need not be explicit "created" or registered; all accounts implicitly exist and are instantiated on first-use. +- Further reading: [Accounts](accounts) + +## Transactions + +- Transaction types: coinbase, token-transfer, contract-deploy, contract-call, poison-microblock. +- Only standard accounts (not contracts) can pay transaction fees. +- Transaction execution is governed by 3 accounts (may or may not be distinct) + 1. _originating account_ is the account that creates, _authorizes_ and sends the transaction + 2. _paying account_ is the account that is billed by the leader for the cost of validating and executing the transaction + 3. _sending account_ is the account that identifies who is currently executing the transaction: this can change as a transaction executes via the `as-contract` Clarity function +- Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. Transactions can be batched or streamed into blocks. The behavior can be controlled by the anchor mode of a transaction. With streaming ([microblocks](microblocks)), a faster confirmation time is possible. +- Two types of authorizations: standard authorization is where originating account is the same as paying account. Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. For instance, developers or service providers could pay for users to call their smart-contracts. Two types of authorizations: standard authorization is where originating account is the same as paying account. _Sponsored_ authorization is where originating account and paying account are distinct. For instance, developers or service providers could pay for users to call their smart-contracts. For instance, developers or service providers could pay for users to call their smart-contracts. +- For sponsored authorization, first a user signs with the originating account and then a sponsor signs with the paying account. +- Mempool limit for concurrent pending transactions is 25 per account +- Pending mempool transactions will be garbage-collected [256 blocks after receipt](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62). With 10 minutes target block time, this would equal ~42 hours With 10 minutes target block time, this would equal ~42 hours With 10 minutes target block time, this would equal ~42 hours With 10 minutes target block time, this would equal ~42 hours +- [Learn more about transaction encoding in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) +- [Transaction signing and verification are described in SIP-005](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) +- All transactions impacting account balance are atomic, a transfer operation can not increment one account’s balance without decrementing another’s. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. However, transactions that perform multiple account actions (for example, transferring from multiple accounts) may partially complete. +- Transactions can include a memo string (max 34 bytes) + +## See also + +- [Read the full Stacks 2.0: Apps and Smart Contracts for Bitcoin whitepaper](https://cloudflare-ipfs.com/ipfs/QmaGgiVHymeDjAc3aF1AwyhiFFwN97pme5m536cHT4FsAW). + +- [Watch Aaron Blankstein video on Stacks whitepaper v2](https://www.youtube.com/watch?v=Wd-Bfe8Sn-Y). diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md new file mode 100644 index 0000000000..da2e561fd1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/testnet.md @@ -0,0 +1,45 @@ +--- +title: Testnet +description: Test your smart contracts and apps +sidebar_position: 12 +--- + +## About testnet + +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnement. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. + +It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. + +### Faucets + +Testnet faucets provide you with free Stacks Token (STX) to test with. These are not the same as STX on mainnet and have no value. There are a couple of different options for getting testnet STX. + +#### Hiro + +You can get STX from the Hiro faucet on the [Hiro Explorer Sandbox](https://explorer.hiro.so/sandbox/faucet?chain=testnet), or using the [API](https://docs.hiro.so/api#tag/Faucets). + +To get STX tokens from within the Explorer Sandbox, navigate to the "Faucet" tab on the left and click "Request STX" button. + +![](/img/stx_faucet.png) + +You can also try out [Stacking](./stacking) by clicking on `I want to stack`. + +:::note +The Explorer Sandbox requires you to login with a Stacks wallet +::: + +#### LearnWeb3 + +Alternatively, you can use the [LearnWeb3 faucet](https://learnweb3.io/faucets). + +![Alt text](lw3-faucet.png) + +### Testnet API + +The hosted Stacks Blockchain API for the testnet is available at this base URL: + +```shell +https://stacks-node-api.testnet.stacks.co/ +``` + +![](/img/api_testnet_status.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md new file mode 100644 index 0000000000..8f44eb1d5f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/transactions.md @@ -0,0 +1,40 @@ +--- +title: Transactions +description: Guide to Stacks 2.0 transactions +sidebar_position: 9 +--- + +## Introduction + +Transactions are the fundamental unit of execution in the Stacks blockchain. Transactions are the fundamental unit of execution in the Stacks blockchain. Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks 2.0 account](accounts), and is retained in the Stacks blockchain history for eternity. This guide helps you understand Stacks 2.0 transactions. This guide helps you understand Stacks 2.0 transactions. This guide helps you understand Stacks 2.0 transactions. + +## Lifecycle + +Transactions go through phases before being finally confirmed, and available for all, on the Stacks 2.0 network. + +![Transaction lifecycle](/img/tx-lifecycle.png) + +- **Generate**: Transactions are assembled according to the encoding specification. +- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. Required signatures are filled in. Required signatures are filled in. Required signatures are filled in. +- **Broadcast**: Transactions are sent to a node. +- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool,"](https://academy.binance.com/en/glossary/mempool) a holding area for all the pending transactions. +- **Process**: Miners review the mempool and select transactions for the next block to be mined. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, smart-contract defined tokens could be minted, or an attempt to call an existing smart contract method could be made. +- **Confirm**: Miners successfully mine blocks with a set of transactions. The transactions inside are successfully propagated to the network. The transactions inside are successfully propagated to the network. The transactions inside are successfully propagated to the network. The transactions inside are successfully propagated to the network. + +:::note A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. ::: ::: ::: + +## Types + +The Stacks 2.0 supports a set of different transaction types: + +| **Type** | **Value** | **Description** | +| ----------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Coinbase | `coinbase` | The first transaction in a new block (an entity holding several transactions). Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. Used to register for block rewards. These are not manually generated and broadcasted like other types of transactions. | +| Token transfer | `token_transfer` | Asset transfer from a sender to a recipient | +| Contract deploy | `smart_contract` | Contract instantiation | +| Contract call | `contract_call` | Contract call for a public, non read-only function | +| Poison Microblock | `poison_microblock` | Punish leaders who intentionally equivocate about the microblocks they package | + +A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). + +:::caution Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](network#read-only-function-calls). ::: Read more about it in the [network guide](network#read-only-function-calls). ::: Read more about it in the [network guide](network#read-only-function-calls). ::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md new file mode 100644 index 0000000000..abada2d864 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/what-is-stacks.md @@ -0,0 +1,91 @@ +--- +title: What is Stacks? +description: An introduction to Stacks +sidebar_position: 1 +--- + +# What is Stacks? + +We can get an idea of the goal and ethos behind Stacks by looking at [how Satoshi envisioned generalizing Bitcoin](https://satoshi.nakamotoinstitute.org/posts/bitcointalk/threads/244/#222) back in 2010: + +> "...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength." + +This is major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. + +This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. + +If that's confusing or you are skeptical, that's understandable, we'll be diving deeper into these ideas as we go through Stacks Academy. + +## Stacks and the Purpose of Blockchain Technology + +When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: + +- Decentralized +- Immutable +- Secure + +You've likely heard of the blockchain trilemma, the problem of trying to balance the decentralization, scalability, and security of a blockchain network. + +Stacks takes the approach of solving this trilemma by separating out chains into layers. + +So at the bottom, you have the foundational layer: Bitcoin. + +Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs. + +Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every 10 minutes or so, making its throughput negligible compared to networks designed for speed like Solana. + +Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). + +Bitcoin is also not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. + +While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. + +## The Stacks Way + +Stacks takes a pyramid approach, where you have the foundational settlement layer at the bottom (Bitcoin), and then a layer on top of that to add smart contracts and programmability (Stacks), and then layers on top of that for scalability and speed (Hiro's Subnets). + +Additionally, there are other layers on top of Bitcoin that serve different purpose and have their own mechanisms and philosophies like Lightning, RSK, and Liquid. + +By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum without all of the drawbacks of having a massively complex chain. + +So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget. + +The only alternative to this model is a federated model like what Liquid uses. Stacks' design decisions operate under the idea that decentralization is more important than rejecting altcoins. + +This is one of the things that separates Stacks from other Bitcoin layers like Lightning. + +Lightning doesn't add any additional functionality to Bitcoin, it simply helps to scale functionality Bitcoin already has and help it operate faster. Lightning is also ephemeral, it has no permanent state that it keeps track of, and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. + +Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles down to Bitcoin (we'll cover this next in the section on Proof of Transfer). + +This is also what separates Stacks from L2 scaling solutions on Ethereum like Polygon or Arbitrum. The benefit we get here is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, and add additional layers for functionality and speed. But if those other layers were to be compromised, that would not affect the foundational layer at all. + +This is an important property when we are talking about building blockchains that are designed to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). + +![btc-stacks](/img/pox-why-bitcoin.png) + +_Sounds like a sidechain_. + +Not quite. We'll get into the technical details of how this works in the next section, but because Stacks records its entire history to Bitcoin, it is at least as hard to re-org the Stacks chain as it is Bitcoin. This is a key differentiator from side chains, which do not have their history recorded to their primary chain. + +Second, Stacks has its own token, it does not represent pegged Bitcoin. While this may ruffle some feathers among some people in the Bitcoin community, it has several advantages. + +First, rather than the security of the Stacks chain relying exclusively on system-specific measures the sidechain has implemented to incentivize validators to produce blocks honestly. + +What does that actually mean? By implementing a token into the Stacks chain, we provide additional economic incentive for miners to produce Stacks blocks honestly. + +This token provides additional incentive in the form of serving as a way to grow the chain. Rather than relying on altruism in order to produce blocks and grow the chain, we can incentivize builders, token-holders, and investors all at the same time by having a token. + +The ICO scams of 2017 put a bad taste in a lot of peoples' mouths, which has justifiably made a lot of people skeptical of every new blockchain project that pops up with a new token. + +But the problem with all of these projects is that they had no actual value, they weren't anchored to anything else of value and provided no real utility. + +With a project like Stacks, we have real utility in the sense of serving as a way to utilize Bitcoin and make it a productive asset **in a decentralized way.** This is a key point, Currently the only way to make Bitcoin productive (meaning use it to make more money) is by giving it to a custodial service or transferring it off the Bitcoin chain by way of something like wBTC on Ethereum. + +Stacks allows us to do this while ultimately still settling to the Bitcoin chain. + +In addition, Stacks allows us to build decentralized and censorship-resistant software utilizing Bitcoin as the foundational settlement layer. Eventually, the goal is to build a network of financial systems and decentralized software products that all utilize Bitcoin as their money. + +A caveat here, a lot of the functionality we've talked about here is still in the early stages, and the highest priority for the ecosystem at the moment is more tightly integrating Stacks with Bitcoin in order to easily use it with Stacks dapps. + +With that context, let's dive into some of the technical details of how Stacks operates, starting with Proof of Transfer. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md new file mode 100644 index 0000000000..0e564fbf44 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/stacks-academy/whitepapers.md @@ -0,0 +1,12 @@ +--- +title: Whitepapers +description: Documents detailing how different pieces of Stacks works +sidebar_position: 2 +--- + +In addition to the documentation here, there are numerous whitepapers detailing how the different pieces of the Stacks ecosystem work. + +- [Stacks 2.0](https://gaia.blockstack.org/hub/1AxyPunHHAHiEffXWESKfbvmBpGQv138Fp/stacks.pdf) +- [Stacks Nakamoto Release](https://assets.stacks.co/stacks.pdf) +- [Proof of Transfer](https://assets.website-files.com/5fcf9ac604d37418aa70a5ab/60072dbb32d416d6b3806935_5f1596b12bcc0800f3dcadcd_pox.pdf) +- [sBTC](https://assets.stacks.co/sbtc.pdf) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md b/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md new file mode 100644 index 0000000000..a4f3d970ca --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/community-tutorials.md @@ -0,0 +1,24 @@ +--- +title: Community Tutorials +description: Tutorials created by various people in the Stacks community +--- + +These tutorials have been created by various members of the Stacks community. Have a tutorial to suggest? View the [contribution guide](http://localhost:3000/docs/contribute/docs) to submit a PR with a new tutorial added. + +## Written Tutorials + +- [Create a server-side rendered Stacks app with Remix](https://micro-stacks.dev/guides/with-remix) +- [Build a Stacks app with Next.js](https://micro-stacks.dev/guides/with-nextjs) +- [Creating a Voting Contract](https://www.clearness.dev/01-voting-clarity-smart-contract/01-getting-started) +- [Building an NFT with Stacks and Clarity](https://blog.developerdao.com/building-an-nft-with-stacks-and-clarity) +- [Minting NFTs with QuickNode](https://www.quicknode.com/guides/web3-sdks/how-to-mint-nfts-on-the-stacks-blockchain) +- [Order Book Contract Walkthrough](https://byzantion.hiro.so/) +- [Build a DEX on Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759) +- [NFT Tutorial](https://docs.hiro.so/tutorials/clarity-nft) +- [Billboard Tutorial](https://docs.hiro.so/tutorials/clarity-billboard) +- [Integrating NFTs Into a Game](https://gamefi-stacks.gitbook.io/gamefistacks/tutorials/integrate-nfts-into-game) +- [Building on Stacks](https://github.com/amoweolubusayo/stacks-clarinet-tutorial) + +## Video Tutorials + +- [Web3 for Bitcoin](https://www.crowdcast.io/e/web3-for-bitcoin/) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md b/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md new file mode 100644 index 0000000000..a0a442d135 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/hello-stacks.md @@ -0,0 +1,759 @@ +--- +title: Hello Stacks (Quickstart) +description: A quick introduction to building dapps with Stacks +sidebar_position: 2 +--- + +# Hello Stacks (Quickstart Tutorial) + +Looking to see what building on Stacks is all about? You're in the right place. + +This tutorial is designed to take you from never having worked with Stacks before to a complete app in about an hour. + +You'll be introduced to all the main concepts and tools utilized to build Stacks dapps, with further resources to continue to learn. + +It does assume a basic familiarity with blockchain and smart contract technology. If you need an intro to those things, we recommend Codecademy's [Intro to Blockchain and Crypto](https://www.codecademy.com/learn/introduction-to-blockchain-and-crypto) course to get up to speed. + +Let's get started. + +## What We're Building + +We're going to be building a very simple practice application called Hello Stacks. Hello Stacks allows users to post a message to the Stacks blockchain and automatically generates a link for others to view that message. + +Here's a brief overview video of what it looks like. + +We'll be utilizing various tools throughout this tutorial, most of which you don't need to have prior experience with. + +It will be helpful, however, for you to be familiar with JavaScript and React to be able to most effectively follow along, as that's what we're going to be using to build the frontend, along with [Vite](https://vitejs.dev/). + +You can either follow along from scratch starting in the next section, or you can download the [starter repo](https://github.com/kenrogers/hello-stacks/tree/starter-branch) with all of the dependencies already set up on GitHub. + +You can also view the finished code in the `master` branch of that same repo. + +Let's get started by getting everything set up. + +## Wallet Setup + +The very first thing you'll need to do is set up the Hiro wallet extension. This is how you can get STX tokens and interact with Stacks dapps. All you need to do right now is visit Hiro's [wallet page](https://wallet.hiro.so/) and install it. We'll set it up later with our dev environment. + +## Code Setup + +If you want to use the starter repo, you can clone that, run `yarn` and move on to the next section, titled '[Writing Our Smart Contract](#writing-our-smart-contract)'. + +Otherwise, follow along if you want to start from scratch. If you are brand new to Stacks and are not familiar with the tooling ecosystem like Clarinet, Stacks.js, etc. I highly recommend following along to get everything set up on your own. + +:::tip +Hiro also has a set of [Stacks.js starters](https://docs.hiro.so/stacksjs-starters) that you can use to quickly get up and running with a new Stacks project. We won't be using them here, but they are an excellent resource. +::: + +The first thing we need to do is scaffold a new project with Vite, the frontend build tool we'll be using. + +We're going to be using [Yarn](https://yarnpkg.com/), but you can also use NPM if you prefer. I'm using Yarn version `1.22.19` for this project and running Node version 18.7.0. You'll need to have both of those installed to follow along. I'm also working on a Mac, but will provide alternative installation instructions for tools like Clarinet as we go. + +:::tip +We recommend [installing and using NVM](https://github.com/nvm-sh/nvm) in order to install Node and easily switch versions. +::: + +We'll have two separate directories for our project, one to handle the smart contracts and one to handle the frontend. Let's start by creating that and changing into it. + +```bash +mkdir hello-stacks && cd hello-stacks +``` + +Then get our frontend scaffolded. + +```bash +yarn create vite frontend --template react +``` + +Next we are going to install Clarinet. Clarinet is a development environment for Stacks created by Hiro. It allows us to set up a local Stacks chain, easily work with Clarity smart contracts (covered next), deploy our contracts, and test them. You can think of it as similar to Hardhat in the Ethereum world. + +Installation instructions vary depending on your system, so I'll refer you to the [Clarinet documentation](https://github.com/hirosystems/clarinet) to get that installed, then come back here to set up our project. + +Still inside the `hello-stacks` directory, let's get our Stacks folder created with the following command. You can name this whatever you want, but I like the frontend/contracts convention. + +```bash +clarinet new contracts +``` + +After this, you should have a `contracts` directory in your project that looks like this. + +![Clarinet directory structure](./clarinet-structure.png) + +There's not much here yet, we'll be creating our contracts in the next section. You'll also see a folder for tests, which are not covered in this tutorial. + +:::note +Some people don't like the `contracts/contracts` structure that results from this naming convention. It's a matter of personal preference what you want to name this top-level folder when you create the Clarinet project. +::: + +Finally, there is a directory called `settings` which contains a few configuration files for how we can interact with each chain. We are primarily concerned with `Devnet.toml` here, as this is how we can set up our local Stacks node for testing purposes. The others mainly come into play when we deploy. + +The `Clarinet.toml` file also provides some configuration options for our smart contracts and Clarinet will add our contracts here when we create them. + +:::tip +Hiro has created an excellent [Clarinet 101](https://www.youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) series on YouTube for getting up to speed on everything Clarinet has to offer. +::: + +Now we need to install some dependencies for working with Stacks and for styling so our app looks halfway decent. I'm a big fan of Tailwind, so we'll be utilizing that in this tutorial. + +Let's get Tailwind installed. We'll need some additional packages from Stacks.js as well, but we'll install those as we go. First make sure you are in the `frontend` directory and install the necessary dependencies for Tailwind. + +```bash +yarn add -D tailwindcss postcss autoprefixer +``` + +and initialize it with + +```bash +npx tailwindcss init -p +``` + +Now we need to tell Tailwind where our content is coming from and change out processing mode to "Just-In-Time" by modifying the `tailwind.config.js` file to look like this. + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + mode: "jit", + content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; +``` + +Add the Tailwind directives to the `index.css` file. + +```css +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now we need to modify our `App.jsx` file to make sure Tailwind is working. + +```js +function App() { + return ( +
+

Hello Stacks

+
+ ); +} + +export default App; +``` + +You can also delete the `App.css` file. + +Now run `yarn dev` and make sure everything is working. Your screen should look like this. + +![Initial app screen](./initial-screen.png) + +Awesome! We have our set up out of the way, now we can start actually coding. We're going to start with our smart contract and learn a bit about Clarity in the process. + +## Writing Our Smart Contract + +Clarity is a smart contract language that has been purpose-built to help developers write safe, secure smart contracts. + +It took a lot of the lessons learned from the Solidity hacks over the years and used them to create something much more secure and safe. + +Stacks smart contracts are written using Clarity and live on the Stacks chain. For a comprehensive introduction to writing Clarity contracts, I highly recommend the book, [Clarity of Mind](https://book.clarity-lang.org/). We'll go over the basics here as we write a simple smart contract, but we are only scratching the surface. + +Before we do that, take a minute to familiarize yourself with what makes Clarity unique and why you might want to build on it by reading just the [Introduction chapter](https://book.clarity-lang.org/ch00-00-introduction.html) of Clarity of Mind. + +Now that you understand why Clarity is useful, let's get started writing our first contract and go over some Clarity concepts along the way. + +The first thing we need to do is generate our new smart contract with Clarinet. Make sure you are in the top level `contracts` folder and generate that. + +```bash +clarinet contract new hello-stacks +``` + +That created a few things for us. First, it created a `hello-stacks_test.ts` file in the `tests` directory. This is how we can use Clarinet to test our smart contracts. We won't cover that here, but you can check out the [TDD with Clarinet](https://dev.to/stacks/test-driven-stacks-development-with-clarinet-2e4i) tutorial for more information on that. + +It also created our actual Clarity file, `hello-stacks.clar` inside the inner `contracts` directory. This is where we'll actually write our smart contract. + +:::tip +If you use VS Code, be sure to install the [Clarity Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=Clarity%20is%20a%20decidable%20Smart,safety%20checks%2C%20debugger%20and%20more.) for a more enjoyable Clarity developer experience. +::: + +If you open up the `Clarinet.toml` file, you'll also see that Clarinet added our new contract there. + +Now let's open up that `hello-stacks.clar` file and get writing our contract. + +You'll see that it set up a bit of a template we can use, with each section commented out. This is a good introduction to some of the common data structures and functions we'll be using in a Clarity contract. + +But we can delete it for now as we'll be writing our own and covering what each does along the way. + +Let's look at the very basic completed Clarity smart contract, then we'll go over what each line does. + +``` +(define-public (write-message (message (string-utf8 500))) + (begin + (print message) + (ok "Message printed") + ) +) +``` + +All we are doing here is defining a new public function called `write-message`. Public means that we can call this function from anywhere, as opposed to private, which would mean only this contract could call it. + +Whenever we call this function, we need to pass it a `message` which is a UTF8 string with a maximum of 500 characters. + +Next we see a block called `begin`. In Clarity, everything is a list inside of a list, so in this function definition, what we are really doing is calling the `define-public` function and passing it to arguments. + +The first is the function signature, which contains the name and the arguments. + +The second argument is the body of the function, but this can only contain a single expression. By wrapping our function body in a `begin` block, we can pass a multi-step function as a single expression. + +Again, there is much more information on how Clarity works in the [Clarity Book](https://book.clarity-lang.org/), this is just a high-level introduction to get you familiar. + +Within this `begin` block we are doing two things. First we are bringing the contents of our message to the blockchain, this will actually post the contents of this message to the chain when we send this transaction, something we'll look at soon. + +Then we are returning a response of `ok`, indicating success, with the message "Message printed". + +Clarity requires return values in all functions. In more complex functions, we would return either a success or error message depending on what action was taken and other logic. + +We can test this right now using the Clarinet console. In the `contracts` folder, run `clarinet console` to open it up and write the following: + +```bash +(contract-call? .hello-stacks write-message u"Hello there") +``` + +Here we are calling the function we just created and passing a message of "Hello there". We prefix that with a `u` to indicate this is a UTF8 string. + +You should get an `ok` message returned here, which indicates that our function was called successfully. + +## Running a Local Stacks Devnet + +One of the coolest features of Clarinet is that it allows us to set up an entire mock Stacks network on our local machine for testing. + +This comes complete with a local block explorer and sandbox environment so we can further test our contracts. + +Make sure you have Docker installed and running, exit out of console with `CMD/CTRL + C` and run `clarinet integrate`. + +It will take a few minutes to get up and running, but then we can open up our local Stacks block explorer. + +:::note +You can [view the live Stacks block explorer](https://explorer.stacks.co/?chain=mainnet) and switch between mainnet and testnet to get familiar with it. +::: + +Once it finishes, visit the local block explorer at `localhost:8000`. You'll be able to see blocks as they are created and also see your `hello-stacks` contract deployment. + +Click on that and copy the contract name, we'll need it for the next step. + +![Explorer view](./explorer-view.png) + +Now go ahead and visit the sandbox by clicking on the 'Sandbox' link up at the top. You'll need to connect with your wallet to use it, but we can also interact with our contract here. + +Be sure to change your network to `Devnet` in your Hiro wallet, then connect. + +:::caution +If you run into funky rendering issues, be sure to change the network URL parameter in the address bar to `testnet`. +::: + +Click on the little function symbol on the left and take the contract name you copied and paste it in the top field there, the name should be automatically populated. + +Hit 'Get Contract' and you should see the function we created there. + +![Loaded hello-stacks contract](./loaded-contract.png) + +Now we can click on that and type in a message to call the function. But if you try to do that now, you might get an error saying you don't have enough STX. + +How do we get STX tokens in our Devnet account? Remember that `Devnet.toml` file Clarinet generates? That determines what accounts have what tokens. + +So now we need to set up our Hiro wallet extension that we set up at the beginning of this tutorial. If you already have an existing Hiro wallet, you'll need to sign out in order to use it with the local Clarinet Devnet. + +:::warning +Make sure you copy your secret key before you sign out. You'll need it to restore your Hiro wallet when you are done developing. +::: + +Go ahead and copy the mnemonic listed in the `Devnet.toml` file and use that to import your local wallet into the Hiro wallet. Then we can use that for interacting with our local Devnet chain. + +Once you do that, go ahead and restart `clarinet integrate`. + +Now we can go back to the sandbox and call that function. You might need to sign out of the sandbox first and reauthenticate. + +When we do, you'll see the Hiro wallet pop up with a transaction confirmation. You'll also see a little notice at the top that no transfers besides fees will occur. + +This is a cool feature of Stacks called Post Conditions. They are outside the scope of this tutorial, but you can learn more about them in the [Understanding Stacks Post Conditions](https://dev.to/stacks/understanding-stacks-post-conditions-e65) tutorial. They are another safety feature to help protect users. + +Now we can go back to the 'Transactions' page, click on this transaction, and see the data that was written to the chain. + +Here you can see a lot of information about the transaction, including the fact that a print event was detected, and what content was printed. + +![Print event log](./event-log.png) + +Let's get our frontend set up so we can see how to do this with a UI and also read this information from the chain. + +## Adding a UI + +For this tutorial, we'll be using [Stacks.js](https://www.hiro.so/stacks-js), a JS library from Hiro that helps us interact with the Stacks chain, our Hiro wallet, and our contracts. Another option is [Micro-Stacks](https://micro-stacks.dev/), a community-created resource. + +Since this is not a React tutorial, I'm going to give you all the boilerplate at once so you can just copy and paste this into `App.jsx` and we'll add the Stacks-specific stuff together. + +```jsx +import { useState } from "react"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + + const connectWallet = () => { + // implement code + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = () => { + // submit transaction + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ +

Hello Stacks

+
+ + +
+
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +We've got a very basic React application set up here that will allow us to add a new message to the Stacks chain and also find the content of a message by entering the transaction ID where the message was posted. + +The first thing we need to do is implement the 'Connect Wallet' functionality. + +In order to do that, we need to add the [`@stacks/connect`](https://github.com/hirosystems/connect/tree/main/packages/connect) package with + +```bash +yarn add @stacks/connect +``` + +:::note +Some users get an error about the `regenerator-runtime` dependency being missing. If that's the case, running `yarn add regenerator-runtime` should fix the issue. +::: + +And import a couple things from it at the top of our `App.jsx` file. + +```jsx +import { + AppConfig, + UserSession, + AuthDetails, + showConnect, +} from "@stacks/connect"; +``` + +Now let's use `AppConfig` which is charge of setting some config options for the wallet to read and `UserSession`, which will actually handle the wallet authentication. + +Below the state declarations, add the following. + +```jsx +const appConfig = new AppConfig(["store_write"]); +const userSession = new UserSession({ appConfig }); +``` + +Here we are setting up an app that needs permission to store and write data to the Stacks chain, and we are instantiating a new user session with that config option passed in. + +We also need to add a few details for the Hiro wallet to display to people interacting with our app. We can do that with the following line: + +```jsx +const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", +}; +``` + +We'll use this when we set up the connect function, which we can do right now in the `connectWallet` function. + +```jsx +const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); +}; +``` + +Here we are using the `showConnect` function to actually trigger the Hiro wallet to show up, allowing the user to authenticate. From there we are triggering a page refresh when the authentication finishes and setting the `userSession` variable, which handles the data for our logged in user. + +At this point you should be able to authenticate with the wallet and have the page refresh, although we can't really do anything with that yet. + +First we need to get our app to be able to read that data. + +We'll add another state variable for our `userData`. + +```jsx +const [userData, setUserData] = useState(undefined); +``` + +And we will also add a `useEffect` call to set this data on page load. + +```jsx +useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } +}, []); + +console.log(userData); +``` + +Now we have access to our authenticated user data, but we need to actually utilize it in our UI. + +The first thing we'll do is hide the 'Connect Wallet' button if there is currently an authenticated user. Change the code that renders our button to the following. + +```jsx +{ + !userData && ( + + ); +} +``` + +We also want to hide the form to submit a message if we are not authenticated. + +```jsx +{ + userData && ( +
+ + +
+ ); +} +``` + +Alright, now we need to actually implement the functionality that will call our `hello-stacks` contract. To do that, we need to use Stacks.js to send a transaction, we'll do that in the `submitMessage` function. + +First we need to install a couple more packages. + +```bash +yarn add @stacks/transactions @stacks/network +``` + +And import a couple things from those at the top. + +```jsx +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; +``` + +We're importing the network we'll be calling the transaction on and a utility helper from the `transactions` package that will help to encode our data in a format that the Clarity contract can understand. + +Now we need to add a new constant to hold the network that we are using. In our case we want to be using `Mocknet`, which we can add using the following right under our current state declarations. + +```jsx +const network = new StacksMocknet(); +``` + +And finally we can add the code to initiate the transaction. + +```jsx +const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); +}; +``` + +What we are doing here is calling our contract (I got the address from the local block explorer) using the `openContractCall` function and passing in some options. + +The contract information, the function we want to call, our function arguments, the network, the app details from earlier, and an action we want to take when we finish calling. + +Note that all values passed to Clarity contracts need to be converted like this. You can see what all the various options are for doing so on the [GitHub page](https://github.com/hirosystems/stacks.js/tree/master/packages/transactions#constructing-clarity-values). + +And if you type a message and hit the submit button, you should see the transaction initiation window pop up. + +![transaction init](./tx-call.png) + +Here's our current `App.jsx` file in its entirety. + +```jsx +import { useEffect, useState } from "react"; +import { + AppConfig, + UserSession, + showConnect, + openContractCall, +} from "@stacks/connect"; +import { StacksMocknet } from "@stacks/network"; +import { stringUtf8CV } from "@stacks/transactions"; + +function App() { + const [message, setMessage] = useState(""); + const [transactionId, setTransactionId] = useState(""); + const [currentMessage, setCurrentMessage] = useState(""); + const [userData, setUserData] = useState(undefined); + + const appConfig = new AppConfig(["store_write"]); + const userSession = new UserSession({ appConfig }); + const appDetails = { + name: "Hello Stacks", + icon: "https://freesvg.org/img/1541103084.png", + }; + + useEffect(() => { + if (userSession.isSignInPending()) { + userSession.handlePendingSignIn().then((userData) => { + setUserData(userData); + }); + } else if (userSession.isUserSignedIn()) { + setUserData(userSession.loadUserData()); + } + }, []); + + console.log(userData); + + const connectWallet = () => { + showConnect({ + appDetails, + onFinish: () => window.location.reload(), + userSession, + }); + }; + + const handleMessageChange = (e) => { + setMessage(e.target.value); + }; + + const submitMessage = async (e) => { + e.preventDefault(); + + const network = new StacksMocknet(); + + const options = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "hello-stacks", + functionName: "write-message", + functionArgs: [stringUtf8CV(message)], + network, + appDetails, + onFinish: ({ txId }) => console.log(txId), + }; + + await openContractCall(options); + }; + + const handleTransactionChange = (e) => { + setTransactionId(e.target.value); + }; + + const retrieveMessage = () => { + // submit transaction + }; + + return ( +
+ {!userData && ( + + )} +

Hello Stacks

+ {userData && ( +
+ + +
+ )} +
+ + +
+ {currentMessage.length > 0 ? ( +

{currentMessage}

+ ) : ( + "" + )} +
+ ); +} + +export default App; +``` + +If you click 'Confirm' you should see the transaction id logged in the console and you can see the transaction in the block explorer. + +![new transaction](./tx-proof.png) + +## Retrieving Messages + +Now that we can write a message to the chain, we also want to add functionality so that we can retrieve a message from the chain. + +We'll do that by having users enter in a transaction ID and we'll query the chain for that transaction and the event data associated with it. + +The Stacks API is perfect for this, and we can query our local devnet chain directly. + +Let's set that up in our `retrieveMessage` function. + +```jsx +const retrieveMessage = async () => { + const retrievedMessage = await fetch( + "http://localhost:3999/extended/v1/tx/events?" + + new URLSearchParams({ + tx_id: transactionId, + }) + ); + const responseJson = await retrievedMessage.json(); + setCurrentMessage(responseJson.events[0].contract_log.value.repr); +}; +``` + +Here we are using `fetch` to call the Stacks API and passing our transaction as a query parameter to get the events and then digging down through that returned data to get the printed message. + +You can view the documentation for this specific API call on [Hiro's website](https://docs.hiro.so/api#tag/Transactions/operation/get_filtered_events). + +If you run this you should see the message printed at the bottom of the screen. + +## Wrapping Up and Next Steps + +Here we've just gone over a very simple and very brief example of a Stacks application. This was meant to give you a high level introduction to the Stacks ecosystem and how you might begin building Stacks dapps. + +There is obviously a lot more to learn, so here are a few good places to continue your learning. + +### Stacks Academy + +Stacks Academy is your guide to all things Stacks. This comprehensive walkthrough will cover key concepts about Stacks so you can learn everything you need to know about how it works. + +[View Stacks Academy](../stacks-academy/) + +### Clarity Book + +The Clarity Book, Clarity of Mind, is the go-to resource for mastering Clarity. It will teach you Clarity development from start to finish so you can begin writing high-quality Clarity smart contracts. + +[Read the Clarity Book](https://book.clarity-lang.org/) + +### Clarity Universe + +Prefer a more immersive experience? Clarity Universe is a start-to-finish guide to learning Clarity, with self-paced option and a guided cohort-based option. + +[Enroll in Clarity Universe](https://clarity-lang.org/universe) + +### Community Tutorials + +There is an ever-growing list of tutorials created by members of the Stacks community so you can learn how to accomplish different tasks and build useful things with Stacks. + +[View Community Tutorials](../tutorials/community-tutorials.md) + +### Next Steps + +Looking to get paid to build something awesome with Stacks? Be sure to see all the different opportunities available to you like full-time jobs, grants, the startup accelerator, and more. + +[Next Steps](../next-steps/) + +### Get Involved + +Finally, be sure to get involved in the Stacks community by [joining Discord](https://discord.gg/5DJaBrf) and [checking out the website](https://stacks.co) to learn more about Stacks. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/index.md new file mode 100644 index 0000000000..1d544c7bc1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/index.md @@ -0,0 +1,11 @@ +--- +title: Tutorials +description: Step-by-step tutorials to learn Stacks development +sidebar_position: 2 +--- + +Looking to learn Stacks development? You're in the right place. + +The quickstart tutorial, Hello Stacks, is designed to give you a quick introduction to Stacks development, which will take about an hour to go through. There is also a comprehensive full-stack tutorial in the works to demonstrate how to build a production-ready dapp using Stacks, complete with integration with BTC. + +You can also view the [Community Tutorials](./community-tutorials) page for a list of community-created tutorials organized by topic. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md b/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md new file mode 100644 index 0000000000..0c72f41b88 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/tutorials/satoshis-ridge.md @@ -0,0 +1,75 @@ +--- +title: Satoshi's Ridge (Deep Dive) +description: A comprehensive overview of building useful Stacks dapps +sidebar_position: 2 +draft: true +--- + +# Satoshi's Ridge (Deep Dive) + +Alright so you've taken the [quickstart tutorial](./hello-stacks.md) and know how to get started building on Stacks. Maybe you've read a bit of [Stacks Academy](../stacks-academy/) and understand why Stacks is unique ad what benefits it provides. + +Now you want to know how to actually build real-world Bitcoin-first dapps using Stacks as the underlying programming layer. + +You're in the right place. + +This comprehensive tutorial is designed to teach you everything you need to know about building Bitcoin dapps. We'll be introducing all the important tools and concepts with links out to additional resources for you to dive deeper into what you need. + +We'll be covering: + +- TDD with Clarity and Clarinet +- Writing robust, secure Clarity contracts +- Utilizing Bitcoin in our Stacks dapp +- Creating a smooth, enjoyable frontend with Remix and Micro-Stacks +- Utilizing oracle data with Redstone +- Off-chain data storage +- Self-hosting our own Stacks node +- Deploying our app to Fly.io +- Deploying our contracts to Stacks testnet with Clarinet +- Potential improvements to make + +Let's do this. + +## Prerequisites + +We won't be covering Bitcoin programming in this tutorial. If you are familiar with the technical aspects of how Bitcoin works (public/private keys, derivation paths, transactions, etc.), we highly recommend giving [Learn Me a Bitcoin](https://learnmeabitcoin.com/) a read. it will arm you with all of the knowledge you'll need to be successful here. + +While you won't need to do any actual Bitcoin programming, it will be very helpful to know how Bitcoin works under the hood to know why we are doing some of the things we are doing here. + +## What is a Bitcoin Dapp? + +The ultimate goal of Stacks is to unlock Bitcoin's potential as latent capital and bring the same functionality as Ethereum has to Bitcoin. But there is a key difference between the two. We can't do that by changing Bitcoin itself. Bitcoin's simplicity and resistance to change may make it more difficult to build on top of, but it is arguably one of its strengths. + +Instead, we need to create separate layers that add additional functionality without modifying Bitcoin itself. Stacks is one such layer. The grand vision of Stacks is to serve as a programming layer for Bitcoin, being completely invisible to the end user in many cases. That is the kind of dapp we'll be building here. + +In order to dive deeper into how we actually go about doing that, check out the [BTC Connection](../stacks-academy/btc-connection.md) section of the docs. + +## What We're Building + +We're going to be building Satoshi's Ridge, a platform for creating a Bitcoin-based mini-society a la Balaji's [Network State](https://thenetworkstate.com/). If you aren't familiar with The Network State, don't worry. We're basically building a platform that enables us to create a decentralized organization and mini-economy based around Bitcoin. + +In The Network State, one of the key ideas is that a network state should have a singular unifying focus. In the case of Satoshi's Ridge, the unifying focus is that of voluntary regulation. + +So the primary goal of Satoshi's Ridge is to create a small network state whose focus is on conceiving of and building voluntary regulation systems. + +What do we mean by voluntary regulation? Let's look at the FDA as an example. The FDA is an example of centralized, involuntary regulation. Medical products cannot be sold without FDA approval (theoretically, but that's another matter) and there is no alternative to getting FDA approval. + +Centralized, involuntary regulation schemes like this are ripe for corruption, because they provide a prime opportunity for corporate interests to influence this centralized entity. + +As an alternative, a decentralized system of various voluntary regulatory agencies would allow consumers to purchase products based on the regulatory organizations they trust to evaluate things effectively. + +Furthermore, by structuring this system as a DAO where members are the ones funding the organization, we significantly reduce the risk of corruption. + +Obviously this is just a tutorial for learning purposes, and there are complex layers of philosophy, politics, economics, and incentive mechanisms at the heart of this, and people will debate about the merits of such systems. + +That is not the point of this tutorial, but only to highlight one of the potential use cases for blockchain technology, and more specifically, Stacks and Bitcoin. + +These types of systemic changes are where blockchains potential really shines. And by using the world's best money, Bitcoin, as the bedrock of this system, we are building it on a solid foundation. + +Bitcoin is an incredible invention, and it generally fixes many of the issues caused by traditional monetary and banking systems, but it doesn't fix human nature. + +If our institutions are still centralized and prone to corruption, Bitcoin only changes the funding source. We need to take the same concepts of decentralization that make Bitcoin so powerful and apply them to our institutions as well, with Bitcoin serving as the economic base layer. + +That's the power of Stacks, and is what we'll be exploring in this deep dive. + +Let's get started building. diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md b/i18n/zh/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md index 35a30f9673..a48fe58598 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/understand-stacks/testnet.md @@ -6,7 +6,7 @@ sidebar_position: 2 ## About testnet -The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. +The testnet is a separate blockchain from the Stacks mainnet analogous to a staging environnment. It's a network used by developers to test their apps, smart contracts, or changes to the protocol in a production-like environment. It produces blocks at roughly the same rate as mainnet; about 1 block every 10 minutes on average. The Stacks testnet is rarely reset. ### Faucet @@ -30,4 +30,4 @@ The hosted Stacks Blockchain API for the testnet is available at this base URL: https://stacks-node-api.testnet.stacks.co/ ``` -![](/img/api_testnet_status.png) +![](/img/api_testnet_status.png) \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md b/i18n/zh/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md index c01d4a2618..2a1fff15ec 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md +++ b/i18n/zh/docusaurus-plugin-content-docs/current/write-smart-contracts/clarity-language/language-functions.md @@ -158,7 +158,12 @@ Returns the integer remainder from integer dividing `i1` by `i2`. In the event o #### output: `int | uint` #### signature: `(pow i1 i2)` #### description: -Returns the result of raising `i1` to the power of `i2`. Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. +Returns the result of raising `i1` to the power of `i2`. Returns the result of raising `i1` to the power of `i2`. In the event of an _overflow_, throws a runtime error. Note: Corner cases are handled with the following rules: + * if both `i1` and `i2` are `0`, return `1` + * if `i1` is `1`, return `1` + * if `i1` is `0`, return `0` + * if `i2` is `1`, return `i1` + * if `i2` is negative or greater than `u32::MAX`, throw a runtime error #### example: ```clarity (pow 2 3) ;; Returns 8 @@ -353,7 +358,7 @@ The `concat` function takes two sequences of the same type, and returns a concat ### as-max-len? #### input: `sequence_A, uint` -#### output: `sequence_A` +#### output: `(optional sequence_A)` #### signature: `(as-max-len? sequence max_length)` sequence max_length) #### description: The `as-max-len?` function takes a sequence argument and a uint-valued, literal length argument. The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` The function returns an optional type. If the input sequence length is less than or equal to the supplied max_length, this returns `(some sequence)`, otherwise it returns `none`. Applicable sequence types are `(list A)`, `buff`, `string-ascii` and `string-utf8`. ` @@ -634,7 +639,7 @@ The `secp256k1-recover?` function recovers the public key used to sign the messa #### output: `bool` #### signature: `(secp256k1-verify message-hash signature public-key)` #### description: -The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. +The `secp256k1-verify` function verifies that the provided signature of the message-hash was signed with the private key that generated the public key. The `message-hash` is the `sha256` of the message. The signature includes 64 bytes plus an optional additional recovery id (00..03) for a total of 64 or 65 bytes. The function throws an unchecked error if the buffers have a wrong length. #### example: ```clarity (secp256k1-verify 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 @@ -1390,4 +1395,4 @@ Like other kinds of definition statements, `impl-trait` may only be used at the ```clarity (impl-trait 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF.token-a.token-trait) (define-public (get-balance (account principal)) (ok u0)) (define-public (transfer? (from principal) (to principal) (amount uint)) (ok u0)) " } (from principal) (to principal) (amount uint)) (ok u0)) -``` \ No newline at end of file +```